两两交换节点
带头结点、需要两个临时指针、较简单
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* tmp1 = cur->next;
ListNode* tmp2 = cur->next->next->next;
cur->next = cur->next->next;
cur->next->next = tmp1;
cur = cur->next->next;
tmp1->next= tmp2;
// delete tmp1,tmp2;
}return dummyhead->next;}
};
删除倒数第n个节点
思路:快慢指针,快指针先移动n+1次,是为了让慢指针移动到待删除结点的前一位
class Solution {
public:
ListNode* removeNthFromEnd(ListNode* head, int n) {
ListNode* dummyhead = new ListNode(0);
dummyhead->next = head;
ListNode* fast = dummyhead;
ListNode* slow = dummyhead;
for(int i =0; i<=n; i++){
if(fast){
fast = fast->next;}
}
while(fast){
fast = fast->next;
slow = slow->next;
}
slow->next = slow->next->next;
return dummyhead->next;
}
};
链表相交
思路:让长的链表的指针先移动到两个链表平齐的位置,然后依次比较(注意比较的是指针,而不是值!!)
class Solution {
public:
ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
ListNode* cura = headA;
ListNode* curb = headB;
int i = 0;int j = 0;
while(cura){
cura = cura->next;
i++;
}
while(curb){
curb = curb->next;
j++;
}
cura = headA;
curb = headB;
//找出链表更长的一个
if(j > i){
swap(i,j);
swap(cura,curb);
}
int gap = i-j;
for(int k =0; k< gap; k++){
cura = cura->next;
} while(cura){
if(cura == curb){
return cura;
}cura = cura->next;
curb = curb->next;
}return NULL;}
};
环形链表
思路是重点,快慢指针间的数学关系