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.
代碼如下:
1 /** 2 * Definition for singly-linked list. 3 * public class ListNode { 4 * int val; 5 * ListNode next; 6 * ListNode(int x) { val = x; } 7 * } 8 */ 9 public class Solution { 10 public ListNode swapPairs(ListNode head) { 11 12 if(head==null||head.next==null) 13 return head; 14 ListNode first=head; 15 ListNode second=first.next; 16 ListNode temp=first; 17 head=second; 18 19 while(first!=null&&second!=null) 20 { 21 temp.next=second; 22 first.next=second.next; 23 temp=first; 24 second.next=first; 25 first=first.next; 26 if(first!=null&&first.next!=null) 27 { 28 second=first.next; 29 } 30 else break; 31 } 32 return head; 33 } 34 35 }