Reverse LinkedList in Pairs:-
Iterative Approach
Iterative Approach
//1->2->3->4->5->6
public Node reverseTheLinkedListInPairs(Node nd){
Node current = nd;
Node temp=null;
Node head=null;
while(current!=null && current.next!=null){
if(temp!=null)
temp.next.next=current.next; //this step joins 2 to 3 when 3 & 4 exchange happens
temp = current.next;//This takes 2 in temp variable
current.next = temp.next; //this step joins 1 to 3
temp.next=current; //this step join 2 to 1
current=current.next; // this steps makes current as 3
if(head==null)
head=temp;// this is basically maintaining the root
}
return head;
}
Recursive Approach
Recursive Approach
public Node reverseTheLinkedListInPairRecursion(Node nd){
if(nd==null || nd.next==null)
return nd;
Node temp = nd.next;
nd.next=temp.next;
temp.next=nd;
nd.next= reverseTheLinkedListInPairRecursion(nd.next);
return temp;
}
No comments:
Post a Comment