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:
Time: O(n) Space: O(1)
/** * Definition for singly-linked list. * class ListNode { * public int val; * public ListNode next; * ListNode(int x) { val = x; next = null; } * } */ public class Solution { // p n nn // 1->2->3->4 // 1<-2->3->4 // 2->1->3->4 // p n // 2->1->3->4
public ListNode swapPairs(ListNode A) { if (A == null || A.next == null) return A; ListNode dummy = new ListNode(0); ListNode prev = dummy; ListNode p = A; while (p != null && p.next != null) { ListNode next = p.next; ListNode nn = next.next; next.next = p; prev.next = next; p.next = nn; prev = p; p = nn; } return dummy.next; } }