题目讲解
24. 两两交换链表中的节点
算法讲解
只需要模拟这个过程就行了,但是需要注意空指针的问题,特别是nnext指针
/**
* 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) {
if(head == nullptr || head->next == nullptr)return head;
ListNode* newhead = new ListNode(-1);
newhead->next = head;
ListNode* prev = newhead;
ListNode* cur = head;
ListNode* Next = head->next;
ListNode* nnext = Next->next;
while(cur && Next)
{
prev->next = Next;
Next->next = cur;
cur->next = nnext;
prev = cur;
cur = nnext;
if(cur)Next = cur->next;
if(Next)nnext = Next->next;
}
prev = newhead->next;
delete newhead;
return prev;
}
};