Leetcode–Swap Nodes in Pairs

The Problem:

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. Basic question with nothing to talk about. General note for linked list: do null check before accessing node’s member.

Java Solution:

 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) {
 *         val = x;
 *         next = null;
 *     }
 * }
public class Solution {
    public ListNode swapPairs(ListNode head) {
        ListNode fkHead = new ListNode(0);
        fkHead.next = head;
        ListNode pre = fkHead;
        ListNode p = head;
        while(p!=null && p.next!= null){
            ListNode temp = p.next.next;
            p.next.next = p;
            pre.next = p.next;
            p.next = temp;
            pre = p;
            p = p.next;
        return fkHead.next;

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s