题目
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.
思路
本题是链表操作,每两个指针就互换一次,这里要注意一个小技巧就是,建立一个指针头,这样可以避免处理head的边界情况,这个是真的很重要啊,一开始自己就是因为犯懒,没指针头,导致各种if-else语句来对临界情况判断,超烦的。
代码
/**
* 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) {
if(head == NULL)
return NULL;
ListNode* helper = new ListNode(0);
helper->next = head; //辅助表头,可以避免处理head的边界情况
ListNode* pre = helper;
ListNode* cur = head;
while(cur!=NULL && cur->next!=NULL)
{
ListNode* next = cur->next->next;
cur->next->next = cur;
pre->next = cur->next;
if(next!=NULL && next->next!=NULL)
cur->next = next->next;
else
cur->next = next;
pre = cur;
cur = next;
}
return helper->next;
}
};