Given a linked list, swap every, adjacent nodes and return its head.
Example
Given 1->2->3->4
, you should return the list as 2->1->4->3
.
Challenge
Your algorithm should use only constant space. Modify the values in the list, only nodes itself can be changed.
Leetcode on the original topic, see my previous blog swap Nodes in Pairs.
Solution One:
classSolution { Public: /** * @param head a listnode * @return a ListNode*/ListNode* Swappairs (listnode*head) {ListNode*dummy =NewListNode (-1), *pre =dummy; Dummy->next =Head; while(Pre->next && pre->next->next) {ListNode*t = pre->Next; Pre->next = t->Next; T->next = t->next->Next; Pre->next->next =T; Pre=T; } returnDummy->Next; }};
Solution Two:
class Solution {public: /* * * @param head a listnode * @return A ListNode */ listnode* swappairs (listnode* head) {if return head; *t = head->Next; Head->next = swappairs (head->next->next); T->next = head; return t; }};
[Lintcode] swap Nodes in Pairs paired switch node