LeetCode24两两交换链表中的节点
递归
ListNode* swapPairs(ListNode* head){
if (head == nullptr || head->next == nullptr) return head;
ListNode* next = head->next;
head->next = swapPairs(next->next);
next->next = head;
return next;
}
迭代
static ListNode* swapPairs(ListNode* head) {
ListNode* virtual_head = new ListNode(-1);
virtual_head->next = head;
ListNode* cur = virtual_head;
while (cur->next != nullptr && cur->next->next != nullptr){
ListNode* temp1 = cur->next;
cur->next = cur->next->next;
temp1->next = cur->next->next;
cur->next->next = temp1;
cur = temp1;
}
return virtual_head->next;
}
LeetCode19 删除链表的倒数第N个节点
常规解法-先计数后遍历
ListNode* removeNthFromEnd(ListNode* head, int n) {
ListNode* p = head;
int sz = 0;
while (p != nullptr){
p = p->next;
sz++;
}
ListNode* virtual_node = new ListNode(-1);
virtual_node->next = head;
ListNode* cur = virtual_node;
n = sz-n;
while (n>0){
cur = cur->next;
n--;
}
cur->next = cur->next->next;
return virtual_node->next;
}
快慢指针
ListNode* removeNthFromEnd(ListNode* head, int n) {
ListNode* virtual_node = new ListNode(-1);
virtual_node->next = head;
ListNode* fast = virtual_node;
ListNode* slow = virtual_node;
while (n-- && fast!= nullptr) fast = fast->next;
fast = fast->next;
while (fast != nullptr){
slow = slow->next;
fast = fast->next;
}
ListNode* temp = slow->next->next;
slow->next = temp;
return virtual_node->next;
}
LeetCode02.07 链表相交
代码
ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
ListNode *p1 = headA;
ListNode *p2 = headB;
int sa = 0, sb = 0;
while (p1 != nullptr){
sa++;
p1 = p1->next;
}
while (p2 != nullptr){
sb++;
p2 = p2->next;
}
ListNode* pa = headA;
ListNode* pb = headB;
if (sa > sb){
int gap = sa - sb;
while (gap--) pa = pa->next;
} else{
int gap = sb - sa;
while (gap--) pb = pb->next;
}
while (pa != nullptr){
if (pa == pb) return pa;
pa = pa->next;
pb = pb->next;
}
return nullptr;
}
LeetCode142 环形链表II
哈希
ListNode *detectCycle(ListNode *head) {
unordered_set<ListNode*> hash;
while (head){
if (hash.count(head)) return head;
hash.insert(head);
head = head->next;
}
return nullptr;
}
快慢指针
思路:
代码:
ListNode *detectCycle(ListNode *head) {
ListNode* slow = head;
ListNode* fast = head;
while (fast != nullptr && fast->next != nullptr){
slow = slow->next;
fast = fast->next->next;
// 慢指针与快指针相遇,说明存在环
if (slow == fast){
// x = (n-1)(y+z)+z
ListNode* index1 = head;
ListNode* index2 = fast;
while (index1 != index2){
index1 = index1->next;
index2 = index2->next;
}
return index2;
}
}
return nullptr;
}