Formatted question description:

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.


could be extended, swap k sublist

eg: k=3, 2->1->4->3->2->1->4->3

2->1->4->3->2->1->4->3  ===>  (2->1->4)->(3->2->1)->4->3  ===>  4->1->2->1->2->3->4->3

method: swapKNodes(ListNode head, int k)

then just extract a method of reversing a sublist, and update to next k nodes


Create a dummyHead that occurs before head, that is, = head. Each time take the two next nodes, and modify the next elements that each node points to. Suppose the current node is temp, and the next two nodes are node1 and node2 respectively, that is, node1 = and node2 =

If node1 == null or node2 == null, then the end of the list is reached, so stop the process. Otherwise, change the nodes as follows. Let = node2, =, and = node1. After these steps, node1 and node2 are swapped. Move temp two steps forward (which should point to node1 after moving two steps), and do swapping for the next nodes. Finally, return



public class Swap_Nodes_in_Pairs {

    public static void main(String[] args) {

        Swap_Nodes_in_Pairs out = new Swap_Nodes_in_Pairs();
        Solution s = Solution();

    public class Solution {
        public ListNode swapPairs(ListNode head) {
//			if (head == null) { // this will not pass while loop below
//				return head;
//			}

            ListNode dummy = new ListNode(0);
   = head;

            ListNode prev = dummy;

            // if only one node left, then no swap
            while ( != null && != null) {

                ListNode first =;
                ListNode second =;

                ListNode third =;

                // swap
       = second;
       = first;
       = third;

                prev =;


All Problems

All Solutions