提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档
一、24两两交换链表中的节点
按照day3卡哥教的虚拟头节点方法自己写的,一开始没写ListNode* dummy = pre;怎么都搞不对,现在其实也没太明白为啥写这句…
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
ListNode* swapPairs(ListNode* head) {
ListNode* pre = new ListNode(0, head);
ListNode* dummy = pre;
ListNode* cur = pre->next;
while (cur && cur->next) {
ListNode* temp = cur->next;
pre->next = temp;
cur->next = cur->next->next;
temp->next = cur;
pre = cur;
cur = cur->next;
}
return dummy->next;
}
};
代码随想录版本:
class Solution {
public:
ListNode* swapPairs(ListNode* head) {
ListNode* dummy = new ListNode(0, head);
ListNode* cur = dummy;
while (cur->next != nullptr && cur->next->next != nullptr) {
ListNode* temp = cur->next;
ListNode* temp1 = cur->next->next->next;
cur->next = cur->next->next;
temp->next = temp1;
cur->next->next = temp;
cur = cur->next->next;
}
return dummy->next;
}
};
二、19删除链表的倒数第N个节点
残存的记忆:
class Solution {
public:
ListNode* removeNthFromEnd(ListNode* head, int n) {
ListNode* dummy = new ListNode(0, head);
ListNode* fast = dummy;
ListNode* slow = dummy;
while (n--) {
fast = fast->next;
}
while (fast->next) {
fast = fast->next;
slow = slow->next;
}
slow->next = slow->next->next;
return dummy->next;
}
};
三、面试题链表相交
class Solution {
public:
ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
if (headA == NULL || headB == NULL) return NULL;
ListNode* node1 = headA;
ListNode* node2 = headB;
int flag = 0;
while (node1) {
if (node1 == node2) {
return node1;
}
else {
if (node1->next || flag) {
node1 = node1->next;
}
else {
node1 = headB;
flag = 1;
}
if (node2->next) {
node2 = node2->next;
}
else {
node2 = headA;
}
}
}
return NULL;
}
};
优化后:
class Solution {
public:
ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
ListNode* node1 = headA;
ListNode* node2 = headB;
while (node1 != node2) {
if (node1) {
node1 = node1->next;
}
else {
node1 = headB;
}
if (node2) {
node2 = node2->next;
}
else {
node2 = headA;
}
}
return node1;
}
};
四、142环形链表II
没什么思路…之前做过,现在忘了咋写了
先判断有没有环,再找入口。
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
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* fast = head;
while (fast != slow) {
fast = fast->next;
slow = slow->next;
}
return fast;
}
}
return NULL;
}
};
总结
通过今天的四道题对链表的理解有所深入,做题也比day3更顺畅了。