-
今日学习的文章链接,或者视频链接
第二章 链表part02
-
自己看到题目的第一想法
-
看完代码随想录之后的想法
24:
注意链表的操作:
class Solution {
public:
ListNode* swapPairs(ListNode* head) {
auto dummyhead = new ListNode(0,head);
auto prev = dummyhead;
auto cur = head;
while (cur != nullptr&&cur->next != nullptr){
auto tmp = cur->next;
auto tmp_next = tmp->next;
prev -> next = tmp;
tmp->next = cur;
cur->next = tmp_next;
prev = cur;
cur = tmp_next;
}
return dummyhead->next;
}
};
19:
class Solution {
public:
ListNode* removeNthFromEnd(ListNode* head, int n) {
ListNode* dummyhead = new ListNode(-1,head);
ListNode* fast = dummyhead;
ListNode* slow = dummyhead;
for(int i = 0; i < n+1; i++){
fast = fast->next;
}
while(fast != nullptr){
fast = fast -> next;
slow = slow -> next;
}
slow -> next = slow -> next -> next;
return dummyhead->next;
}
};
不用dummyhead版本,各种处理边界条件:
class Solution {
public:
ListNode* removeNthFromEnd(ListNode* head, int n) {
//ListNode* dummyhead = new ListNode(-1,head);
ListNode* fast = head;
ListNode* slow = head;
int flag = 1;
for(int i = 0; i < n+1; i++){
if (fast != nullptr)
{
fast = fast->next;
}else{
flag = 0;
break;
}
}
while(fast != nullptr){
fast = fast -> next;
slow = slow -> next;
}
if (flag==1||slow!=head&&slow -> next != nullptr){
slow -> next = slow -> next -> next;
}else{
return head->next;
}
return head;
}
};
02.07
奇妙解法:
class Solution {
public:
ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
auto curA = headA;
auto curB = headB;
while (curA != curB){
if (curA == nullptr){
curA = headB;
}else{
curA = curA->next;
}
curB = curB == nullptr?headA:curB->next;
}
return curA;
}
};
142:
class Solution {
public:
ListNode *detectCycle(ListNode *head) {
auto fast = head;
auto slow = head;
//fast 走两步,所以判断fast和fast->next
while (fast != nullptr && fast->next != nullptr) {
fast = fast->next->next;
slow = slow->next;
if (fast == slow) {
break;
}
}
if (fast == nullptr || fast->next == nullptr) {
return nullptr; // No cycle found
}
fast = head;
while(fast!=slow){
fast = fast->next;
slow = slow->next;
}
return fast;
}
};
-
自己实现过程中遇到哪些困难
-
今日收获,记录一下自己的学习时长