Given a linked list, swap every two adjacent nodes and return its head.
For example,
Given 1->2->3->4
, you should return the list as 2->1->4->3
.
Your algorithm should use only constant space. You may not modify the values in the list, only nodes itself can be changed.
解法:先画图搞清楚指针变换的关系,然后再改。这道题真他妈难,写不粗来,参考了别人的代码。巧妙地用了一个中间变量。
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public: ListNode* swapPairs(ListNode* head) { ListNode* current = head; ListNode* pnext = NULL; ListNode* pre = NULL; ListNode* prePre = NULL; while(current != NULL && current->next != NULL) { pre = current; current = current->next; pnext = current->next; if(pre == head) head = current; //这是首次进行循环头指针的改变 if(prePre) prePre->next = current; //这步是关键步骤,一开始没想到过 current->next = pre; pre->next = pnext; prePre = pre; //保存前指针 current = pnext; } return head; } };