4/03/2014

Leetcode -- Swap Nodes in Pairs

/**  
  * 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 * dummyHead = new ListNode(-1);  
     dummyHead->next = head;  
     ListNode * p1 = dummyHead;  
     ListNode * p2 = head;  
     while(p2 != NULL && p2->next != NULL){  
      ListNode * temp = p2->next->next;  
      p1->next = p2->next;  
      p2->next->next = p2;  
      p2->next = temp;  
      p1 = p2;  
      p2 = temp;  
     }   
     return dummyHead->next;  
   }  
 };

No comments: