24.两两交换链表中的节点
class Solution {
public:
ListNode* swapPairs(ListNode* head) {
ListNode* dummyhead = new ListNode(-1);
dummyhead->next = head;
ListNode* pre = head;
ListNode* cur;
ListNode* ppre = dummyhead;
while(pre && pre->next != nullptr){
cur = pre->next;
ListNode* temp = cur->next;
// pre和cur换位
ppre->next = cur;
cur->next = pre;
pre->next = temp;
// 移动
pre = temp;
ppre = pre;
}
return dummyhead->next;
}
};
19.删除链表的倒数第N个节点
class Solution {
public:
ListNode* removeNthFromEnd(ListNode* head, int n) {
ListNode* dummmyhead = new ListNode(0);
dummmyhead->next = head;
ListNode* tail = dummmyhead;
ListNode* pre = dummmyhead;
ListNode* cur = dummmyhead->next;
// pre和tail差n个节点
while(n--){
tail = tail->next;
}
//pre是倒数n+1,删除cur
while(tail && tail->next){
tail = tail->next;
pre = pre->next;
cur = cur->next;
}
pre->next = cur->next;
return dummmyhead->next;
}
};
添加虚拟头节点时忘记连接head,导致编译一直出错
链表相交
class Solution {
public:
ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
int len1 = 0;
int len2 = 0;
ListNode* cur1 = headA;
ListNode* cur2 = headB;
while(cur1){
cur1 = cur1->next;
len1++;
}
while(cur2){
cur2 = cur2->next;
len2++;
}
while(len1 > len2){
headA = headA->next;
len1--;
}
while(len1 < len2){
headB = headB->next;
len2--;
}
while(headA && headB){
if(headA == headB){
return headA;
}
headA = headA->next;
headB = headB->next;
}
return nullptr;
}
};
环形链表II
class Solution {
public:
ListNode *detectCycle(ListNode *head) {
ListNode* dummmyhead = new ListNode(-1);
dummmyhead->next = head;
unordered_set<ListNode*> set;
ListNode* cur = head;
while(cur){
if(set.find(cur) != set.end()){
return cur;
}
set.insert(cur);
cur= cur->next;
}
return nullptr;
}
};
一开始用双指针做,不过只判断了有没有环,起点没有找到,干脆直接用set去存访问过的节点,只要重复访问一个节点就是环的入口
再贴一下双指针的做法
class Solution {
public:
ListNode *detectCycle(ListNode *head) {
ListNode* fast = head;
ListNode* slow = head;
while(fast != NULL && fast->next != NULL) {
slow = slow->next;
fast = fast->next->next;
// 快慢指针相遇,此时从head 和 相遇点,同时查找直至相遇
if (slow == fast) {
ListNode* index1 = fast;
ListNode* index2 = head;
while (index1 != index2) {
index1 = index1->next;
index2 = index2->next;
}
return index2; // 返回环的入口
}
}
return NULL;
}
};