Given a linked list, swap every two adjacent nodes and return its head.
Example:
Given1->2->3->4
, you should return the list as2->1->4->3
.
Note:
- Your algorithm should use only constant extra space.
- You may not modify the values in the list's nodes, only nodes itself may 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 * t1 = head,* t2 = head,* pre =NULL, *after =head;
if (head == NULL) return NULL;
if (head->next == NULL) return head;
ListNode* result = head->next;
while(t2!=NULL&&t2->next!=NULL){
t2 = t2->next;
after = t2->next;
t2->next = t1;
t1->next = after;
if (pre!=NULL) pre->next = t2;
pre = t1;
t1 = after;
t2 = after;
}
return result;
}
};
别人的做法第二遍回来再看。