Advertisement
gelita

swap nodes in pairs(nodes not values)

Mar 30th, 2020
755
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 5 0.67 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. class Solution {
  10.     public ListNode swapPairs(ListNode head) {
  11.         ListNode temp = new ListNode(0);
  12.         temp.next = head;
  13.         ListNode curr = temp;
  14.         while(curr.next != null && curr.next.next != null){
  15.             ListNode first = curr.next;
  16.             ListNode second = curr.next.next;
  17.             first.next = second.next;
  18.             second.next = first;
  19.             curr.next = second;
  20.             curr.next.next = first;
  21.             curr = first;
  22.         }
  23.         return temp.next;
  24.     }
  25. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement