1. 程式人生 > >Leetcode刷題記——24. Swap Nodes in Pairs(交換成對結點)

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.

Subscribe to see which companies asked this question


二、解題思路:

easy題,非常簡單,不要想著交換連結串列的指標,交換值就行了。

(1)之後在做完題後,把最基本的例子跑一遍,不要再寫死迴圈了!

三、原始碼:

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
public class Solution 
{
    public ListNode swapPairs(ListNode head) 
    {
     ListNode a = head;
     int temp;
     if (head == null) return null;
     while (a.next != null)
     {
    	 temp = a.next.val;
    	 a.next.val = a.val;
    	 a.val = temp;
    	 if (a.next.next != null)
    		 a = a.next.next;
    	 else 
    		 a = a.next;
    	 
     }
     return  head;
    }
    public void print(ListNode root)     
    {    
      System.out.print(root.val + "\t");    
      if (root.next != null)    
    	  print(root.next);    
    }    
    public static void main (String args[])
    {
    	 ListNode l1 = new ListNode(2);    
         ListNode a = l1;    
         a.next = new ListNode(3);    
         a = a.next;    
         a.next = new ListNode(4);    
         a = a.next;    
         a.next = new ListNode(1); 
         //b.next = new ListNode(4);    
         Solution s = new Solution();    
         s.print(s.swapPairs(l1));    
    }
}