InterviewBit - Swap list nodes in pairs  

by ne on 2021-09-22 under Algo tagged with interviewbit

This problem is a property of InterviewBit (www.interviewbit.com).
Full details of the question, and if you want to try it out yourself, proceed to interviewbit : Original problem

Here's the implementation:


/**
 * Definition for singly-linked list.
 * class ListNode {
 *     public int val;
 *     public ListNode next;
 *     ListNode(int x) { val = x; next = null; }
 * }
 */
public class Solution {
    public ListNode swapPairs(ListNode A) {
        ListNode temp=A;
        while(temp!=null){
            int a=temp.val;
            if(temp.next!=null){
                ListNode prev=temp;
                temp=temp.next;
                int b=temp.val;
                prev.val=b;
                temp.val=a;
            }
            temp=temp.next;
        }
        return A;
    }
}