leetcode-142 环形链表II
生活随笔
收集整理的這篇文章主要介紹了
leetcode-142 环形链表II
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
給定一個鏈表,返回鏈表開始入環的第一個節點。 如果鏈表無環,則返回 null。
為了表示給定鏈表中的環,我們使用整數 pos 來表示鏈表尾連接到鏈表中的位置(索引從 0 開始)。 如果 pos 是 -1,則在該鏈表中沒有環。
說明:不允許修改給定的鏈表。
示例 1:
輸入:head = [3,2,0,-4], pos = 1 輸出:tail connects to node index 1
解釋:鏈表中有一個環,其尾部連接到第二個節點。
方法一: 集合set進行環的判斷
當想要插入節點到set中之前需確認set中沒有當前節點,如果有則為環,沒有即可插入
ListNode *detectCycle(ListNode *head) {if (head == NULL) return NULL;set<ListNode *> node_set;node_set.insert(head);head = head -> next;while(head) {if (node_set.find(head) == node_set.end()) {node_set.insert(head);} else {return head;}head = head -> next;}return NULL;
}
方法二:快慢指針
ListNode *detectCycle(ListNode *head) {ListNode *fast = head;ListNode *slow = head;ListNode *meet = NULL;while(fast && slow) {fast = fast -> next;slow = slow -> next;if (fast) {fast = fast -> next;if (fast == slow) { //找到相遇的節點meet = fast;break;}} else {return NULL;}}if (meet == NULL) {return NULL;}/*兩個指針分別從相遇節點和頭節點一起移動,當相等時則為環的起始節點*/while(!(meet == head)) { meet = meet -> next;head = head -> next;}return meet;
}
總結
以上是生活随笔為你收集整理的leetcode-142 环形链表II的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 苹果6plus现价是多少?
- 下一篇: leetcode-86 分隔链表