c++ 怎样连接两个链表_LeetCode | 链表的入口,一文帮你搞定“环形链表”(python版,最简单解析)...
鏈表節(jié)點(diǎn)的定義
鏈表作為一種數(shù)據(jù)結(jié)構(gòu),由鏈表節(jié)點(diǎn)互相連接構(gòu)成。
鏈表節(jié)點(diǎn)包含自身的數(shù)據(jù)和一個(gè)指向下一節(jié)點(diǎn)的指針。
由于節(jié)點(diǎn)自身的結(jié)構(gòu)特點(diǎn),鏈表可以僅由一個(gè)頭結(jié)點(diǎn)表示。
環(huán)形鏈表
顧名思義,環(huán)形鏈表指鏈表構(gòu)建過程中,存在環(huán),即鏈表中某一節(jié)點(diǎn)從自身出發(fā),最后可以訪問到自身。
判斷鏈表是否為環(huán)形鏈表
- leecode141 LinkedListCycle
這題只需記住,快慢指針。至于中間的判斷條件,再慢慢debug。
class Solution:"""@param head: The first node of linked list.@return: True if it has a cycle, or false"""def hasCycle(self, head):if head is None:return False# 快慢指針,快的走兩步,慢的走一步fast = headslow = headwhile(fast.next and fast.next.next):fast = fast.next.nextslow = slow.nextif fast == slow:return Truereturn False查找環(huán)形鏈表的入口
- leetcode142 LinkedListCycleII
在快慢指針的基礎(chǔ)上,如果快慢指針重合,將快慢指針恢復(fù)成單步指針x,z,讓x指針從頭開始,z指針從重合位置開始,當(dāng)x、z指針再次相遇即為環(huán)形鏈表的入口Y。這可以通過理論證明,感興趣搜一下。
class Solution(object):def detectCycle(self, head):""":type head: ListNode:rtype: ListNode"""fast = headslow = headwhile(fast.next and fast.next.next):fast = fast.next.nextslow = fast.nextif fast == slow:breakif fast is None:return Nonefast = headwhile(fast != slow):fast = fast.nextslow = slow.nextreturn slow相交鏈表
除了在單獨(dú)一條環(huán)形鏈表找節(jié)點(diǎn)入口,還有一種情況是求解兩條相交鏈表的入口。
- leetcode160 getIntersectionNode
這題理論分析上簡(jiǎn)單一點(diǎn)。
假設(shè)鏈表1長(zhǎng)度(a+c),鏈表2長(zhǎng)度(b+c),姑且a<b;若同時(shí)遍歷,x節(jié)點(diǎn)在鏈表1走到尾時(shí),y節(jié)點(diǎn)在鏈表2距離尾(b-a); 這時(shí)使走到尾的x節(jié)點(diǎn)從鏈表2頭開始,y節(jié)點(diǎn)在鏈表2走到尾時(shí),x在鏈表2頭已經(jīng)走了(b-a)個(gè)節(jié)點(diǎn)。
此時(shí)然y節(jié)點(diǎn)在鏈表1頭開始,同時(shí)單步移動(dòng)x、y節(jié)點(diǎn),由于x節(jié)點(diǎn)比y節(jié)點(diǎn)多走了b-a,下次首次相遇一定是在兩鏈表的交點(diǎn)。class Solution(object):def getIntersectionNode(self, headA, headB):""":type headA, headB: ListNode:rtype: ListNode"""# 算出長(zhǎng)鏈表比短鏈表多的長(zhǎng)度,讓長(zhǎng)鏈表多走k步if headA is None or headB is None:return NonetmpA = headAtmpB = headBlenA = 0lenB = 0while(tmpA):tmpA = tmpA.nextlenA += 1while(tmpB):tmpB = tmpB.nextlenB += 1if lenA > lenB:for i in range(lenA - lenB):headA = headA.nextelse:for i in range(lenB - lenA):headB = headB.nextwhile(headA != headB):headA = headA.nextheadB = headB.nextreturn headA
更多精彩文章,歡迎關(guān)注公眾號(hào)“Li的白日囈語”。
總結(jié)
以上是生活随笔為你收集整理的c++ 怎样连接两个链表_LeetCode | 链表的入口,一文帮你搞定“环形链表”(python版,最简单解析)...的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
 
                            
                        - 上一篇: 彩虹六号围攻多少钱啊?
- 下一篇: springboot tomcat默认线
