24. 两两交换链表中的节点
![image.png](https://p3-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp/6b52140970264dc68234ba92976a3954~tplv-k3u1fbpfcp-watermark.image?)
```/**
* 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* dummy = new ListNode(0);
dummy->next = head;
ListNode* cur = dummy;
while(cur->next != NULL && cur->next->next != NULL){ //先后顺序不能乱,否则会报空指针异常。
ListNode* tmp = cur->next;
ListNode* tmp1 = cur->next->next->next; //加入交换节点1和2,节点1和3会容易丢失,先保存。
cur->next = cur->next->next;
cur->next->next = tmp;
tmp->next = tmp1;
cur = cur->next->next; //cur要向后移动两位,继续对后面的节点进行操作
}
return dummy->next;
}
};
```
19.删除链表的倒数第N个节点
![image.png](https://p3-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp/cd849022172a406cbc997a8f87827af9~tplv-k3u1fbpfcp-watermark.image?)
```/**
* 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* dummy = new ListNode(0);
dummy->next = head;
ListNode* slow = dummy;
ListNode* fast = dummy;
while(n-- && fast != NULL){
fast = fast->next;
}
fast = fast->next; //快指针必须再先走一步,要让慢指针指向删除的那个节点的上一个
while(fast != NULL){
fast = fast->next;
slow = slow->next;
}
ListNode* tmp =slow->next;
slow->next = slow->next->next;
delete tmp; //还要把这个节点从内存中删掉
return dummy->next;
}
};
```