Day04_链表
5. 两两交换链表中的节点
24. 两两交换链表中的节点 思路:
按照下如图模拟
class Solution {
public:
ListNode* swapPairs(ListNode* head) {
ListNode* _dummyHead = new ListNode(0);
_dummyHead->next = head;
ListNode* cur = _dummyHead;
while (cur->next && cur->next->next) {
ListNode* tmp = cur->next;
ListNode* tmp_next_pair = cur->next->next->next;
cur->next = cur->next->next;
cur->next->next = tmp;
tmp->next = tmp_next_pair;
cur = cur->next->next;
}
return _dummyHead->next;
}
};
6. 删除链表的倒数第 N 个结点
19. 删除链表的倒数第 N 个结点 思路:
本来想两次遍历,看到卡哥的双指针,直呼挺妙,虽然复杂度也是
O
(
n
)
O(n)
O(n) 利用双指针间格n个位置,就可以在fast指针移动到链表结尾时,slow指针停在要删除的节点前。
class Solution {
public:
ListNode* removeNthFromEnd(ListNode* head, int n) {
ListNode* _dummyHead = new ListNode(0);
_dummyHead->next = head;
ListNode* fast_index = _dummyHead;
ListNode* slow_index = _dummyHead;
while(n-- && fast_index) {
fast_index = fast_index->next;
}
while(fast_index->next) {
fast_index = fast_index->next;
slow_index = slow_index->next;
}
slow_index->next = slow_index->next->next;
return _dummyHead->next;
}
};
7. 链表相交
面试题 02.07. 链表相交 思路:
又不是自己想的,呜呜呜 显然不能是利用两个节点的值相等作为判断依据,要判断指针地址一致才行。如何让两个节点能够在相交处相遇呢?就让两个链表从头部对齐变为尾部对齐,接下来一起以相同的速度往后遍历,一定会在相交的点处相遇。
class Solution {
public:
ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
ListNode* A_pos = headA;
ListNode* B_pos = headB;
int lenA = 0, lenB = 0;
while(A_pos) {
lenA++;
A_pos = A_pos->next;
}
while(B_pos) {
lenB++;
B_pos = B_pos->next;
}
int delta_len = lenA - lenB;
A_pos = headA;
B_pos = headB;
if (delta_len < 0) {
swap(lenA, lenB);
swap(A_pos, B_pos);
delta_len = abs(delta_len);
}
while(delta_len--) {
A_pos = A_pos->next;
}
while (A_pos && A_pos != B_pos) {
A_pos = A_pos->next;
B_pos = B_pos->next;
}
return A_pos;
}
};
8. 环形链表 II
142. 环形链表 II 思路:
实用两个指针,一快一慢,快指针一次走两步,慢指针一次走一步。如果两个指针相交,则有环。然后快指针在交点处,慢指针在起点处,以步长为1运动,直到相遇点,为环的交点。
class Solution {
public:
ListNode *detectCycle(ListNode *head) {
ListNode* fast_index = head;
ListNode* slow_index = head;
while(fast_index && slow_index) {
fast_index = fast_index->next;
slow_index = slow_index->next;
if (fast_index == NULL || slow_index == NULL) return NULL;
fast_index = fast_index->next;
if (fast_index == slow_index) break;
}
if (fast_index == NULL || slow_index ==NULL) return NULL;
slow_index = head;
while (fast_index != slow_index) {
fast_index = fast_index->next;
slow_index = slow_index->next;
}
return fast_index;
}
};
|