Description
Given a linked list, swap every two adjacent nodes and return its head.
Example
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.
思路
- 首先使用两个指针指向要交换的节点,并且使用另外一个指针用来连接两对交换节点,也就是代码中的pre
- 考虑好边界情况吧。算是个细心活
代码
/**
* 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 *res = NULL, *ptr = NULL, *cur = NULL, *pre = NULL;
if(!head || !head->next) return head;
ptr = head;
cur = head->next;
while(ptr && cur){
//剩下链表的头结点
head = cur->next;
//交换
cur->next = ptr;
ptr->next = head;
//头结点
if(!res)
res = cur;
//前面交换的后一个接上后面交换的前一个
if(!pre)
pre = ptr;
else{
pre->next = cur;
pre = ptr;
}
ptr = head;
if(head)
cur = head->next;
}
return res;
}
};