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) {
    	if(head == NULL ||head->next == NULL) return head;
    	ListNode dummy(-1);
    	ListNode *tail = &dummy;
    
    	while(head && head->next)
    	{
    		ListNode *tmp = head->next->next;
    		tail->next = head->next;
    		tail->next->next = head;
    		tail = head;
    		head = tmp;
    	}
    
    	tail->next = head;
    	head = dummy.next;
    
    	return head;
    }
};

 

 

/**
 * 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 ||head->next == NULL) return head;
		ListNode *cur = head->next->next;
		ListNode *tail = head;
		//tail->next = cur->next;
		head->next->next = tail;
		head = head->next;
    
    	while(cur && cur->next)
    	{
    		ListNode *tmp = cur->next->next;
    		tail->next = cur->next;
    		tail->next->next = cur;
    		tail = cur;
    		cur = tmp;
    	}
    
    	tail->next = cur;
    
    	return head;
    }
};

 

posted on 2015-01-04 10:30  风云逸  阅读(259)  评论(0)    收藏  举报