Leetcode 24 两两交换链表中的节点
题目链接:两两交换链表中的节点
Solution:
- 迭代法
需要注意的点是node1->next要先赋值,否则会找不到链表后边的数据。
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 *node1 = cur->next;
ListNode *node2 = cur->next->next;
cur->next = node2;
node1->next = node2->next;
node2->next = node1;
cur = node1;
}
return dummyhead->next;
}
};
Leetcode 19.删除链表的倒数第N个节点
题目链接:删除链表的倒数第N个节点
Solution:
- 快慢指针
本题要注意快慢指针的起始位置,因为slow要在待删除节点的前一个位置才可以进行删除操作
class Solution {
public:
ListNode* removeNthFromEnd(ListNode* head, int n) {
ListNode* dummyhead = new ListNode(0);
dummyhead->next = head;
ListNode* fast = head;
ListNode* slow = dummyhead;
for (int i = 0; i < n; ++i) {
fast = fast->next;
}
while (fast) {
fast = fast->next;
slow = slow->next;
}
slow->next = slow->next->next;
return dummyhead->next;
}
};
Leetcode 链表相交
题目链接:链表相交
Solution:
遍历到结尾后,指向另一个链表
class Solution {
public:
ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
ListNode *curA = headA;
ListNode *curB = headB;
if (curA == nullptr || curB == nullptr)
return nullptr;
while(curA != curB) {
if(curA == NULL) {
curA = headB;
} else {
curA = curA->next;
}
if(curB == NULL) {
curB = headA;
} else {
curB = curB->next;
}
}
return curA;
}
};
Leetcode 142.环形链表二
题目链接:链表相交
Solution:
class Solution {
public:
ListNode *detectCycle(ListNode *head) {
ListNode *fast = head;
ListNode *slow = head;
while(fast && fast->next) {
fast = fast->next->next;
slow = slow->next;
if(fast == slow) {
ListNode *index1 = head;
ListNode *index2 = fast;
while(index1 != index2) {
index1 = index1->next;
index2 = index2->next;
}
return index1;
}
}
return NULL;
}
};