Advertisement
Guest User

Untitled

a guest
May 28th, 2015
234
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 0.95 KB | None | 0 0
  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.         }
  15.         ListNode f = head;
  16.         ListNode s = head.next;
  17.         ListNode last = head;
  18.         while(f!=null && s!=null){
  19.             //swap nodes
  20.             ListNode temp = s.next;
  21.             s.next = f;
  22.             f.next = temp;
  23.             if(last==head){
  24.                 head = s;    
  25.             }
  26.            
  27.             else{
  28.                 last.next = s;
  29.             }
  30.            
  31.             if (temp==null){
  32.                 return head;
  33.             }
  34.             else{
  35.                 f = temp;
  36.                 s = temp.next;
  37.                 last = f;
  38.             }
  39.         }
  40.         return head;
  41.     }
  42. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement