2015年9月18日星期五

Leetcode 24 Swap Nodes in Pairs

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.

Solution 1: Normal LinkedList problem, use dummy head technique.
 public class Solution {  
   public ListNode swapPairs(ListNode head) {  
     ListNode dummy=new ListNode(0);  
     dummy.next=head;  
     ListNode i=dummy;  
     while (i.next!=null && i.next.next!=null) {  
       ListNode j=i.next;  
       ListNode k=j.next;  
       ListNode temp=k.next;  
       i.next=k;  
       k.next=j;  
       j.next=temp;  
       i=j;  
     }  
     return dummy.next;  
   }  
 }  

没有评论:

发表评论