学习资料
www.programmercarl.com/%E9%9D%A2%E…
24
第一思路
从1开始记录链表的奇偶为判断
/**
* 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* dummyhead = new ListNode(0);
dummyhead->next = head;
ListNode* cur = dummyhead;
//如果链表为空,直接返回
if (cur->next == nullptr) {
return dummyhead->next;
} else {
int count = 1;
while (cur->next) {
if (count / 2 == 0) {
if (cur->next->next) {
if (cur->next->next->next){
ListNode* temp = cur->next->next->next;
ListNode* temp1 = cur->next;
cur->next = cur->next->next;
cur->next->next = temp1;
cur->next->next->next = temp;
cur = cur->next;
count++;
}
else {
ListNode* temp = cur->next;
cur->next = cur->next->next;
cur->next->next = temp;
return dummyhead->next;
}
}
else {
return dummyhead->next;
}
}
else {
cur = cur->next;
count++;
}
}
}
return dummyhead->next;
}
};
结果解答错误
总结
边界条件想复杂了,其实只需要判断next和next.next就行
19
第一思路
先写一个辅助函数求出节点个数count,倒数第n个节点,就是整数第count - n 个
/**
* 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* removeNthFromEnd(ListNode* head, int n) {
ListNode* dummyHead = new ListNode(0);
dummyHead->next = head;
ListNode* cur = dummyHead;
int m = Count(head) - n;
while (m--) {
cur = cur->next;
}
ListNode* temp = cur->next;
cur->next = cur->next->next;
delete temp;
return dummyHead->next;
}
int Count(ListNode* head) {
int count = 0;
while (head) {
count++;
head = head->next;
}
return count;
}
};
一次通过
总结
还是想不到这里可以用双指针
160
第一思路
暴力解法,结果超时
class Solution {
public:
ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
ListNode* curA = headA;
ListNode* curB = headB;
while(curA) {
while (curB) {
if (curB == curA) {
return curB;
}
}
curB = headB;
curA = curA->next;
}
return nullptr;
}
};
142
第一思路
完全想不到