[Approach] Two Pointers + Pointer Manipulation on Linked List - O(n) Time and O(1) Space
The idea is to first count the total length of the linked list, then locate the k-th node from the beginning and the k-th node from the end using two separate traversals. Once both nodes (and their previous nodes) are found, we adjust the links of their previous nodes and swap their next pointers.
Additional if the k-th node from the beginning is the head, then after the swap the head should be updated to point to the k-th node from the end. Similarly, if the k-th node from the end is the tail, then after the swap the tail should be updated to point to the k-th node from the beginning.
C++
#include<iostream>usingnamespacestd;// Node class for singly linked listclassNode{public:intdata;Node*next;Node(intd){data=d;next=nullptr;}};Node*swapKth(Node*head,intk){if(!head)returnhead;// Count lengthintn=0;Node*temp=head;while(temp){n++;temp=temp->next;}// if k is more than length, no swapif(k>n)returnhead;// if kth from start and end are same, no swapif(2*k-1==n)returnhead;// find kth node from start and its prevNode*prevX=nullptr;Node*x=head;for(inti=1;i<k;i++){prevX=x;x=x->next;}// find kth node from end and its prevNode*prevY=nullptr;Node*y=head;for(inti=1;i<n-k+1;i++){prevY=y;y=y->next;}// adjust previous pointersif(prevX)prevX->next=y;if(prevY)prevY->next=x;// swap next pointersNode*tempNext=x->next;x->next=y->next;y->next=tempNext;// change head if neededif(k==1)head=y;if(k==n)head=x;returnhead;}// utility to print listvoidprintList(Node*head){while(head){cout<<head->data;if(head->next)cout<<" -> ";head=head->next;}cout<<endl;}intmain(){Node*head=newNode(5);head->next=newNode(10);head->next->next=newNode(8);head->next->next->next=newNode(5);head->next->next->next->next=newNode(9);head->next->next->next->next->next=newNode(3);intk=2;head=swapKth(head,k);printList(head);return0;}
Java
classNode{intdata;Nodenext;Node(intd){data=d;next=null;}}classGfG{staticNodeswapKth(Nodehead,intk){if(head==null)returnhead;// Count lengthintn=0;Nodetemp=head;while(temp!=null){n++;temp=temp.next;}// if k is more than length, no swapif(k>n)returnhead;// if kth from start and end are same, no swapif(2*k-1==n)returnhead;// find kth node from start and its prevNodeprevX=null;Nodex=head;for(inti=1;i<k;i++){prevX=x;x=x.next;}// find kth node from end and its prevNodeprevY=null;Nodey=head;for(inti=1;i<n-k+1;i++){prevY=y;y=y.next;}// adjust previous pointersif(prevX!=null)prevX.next=y;if(prevY!=null)prevY.next=x;// swap next pointersNodetempNext=x.next;x.next=y.next;y.next=tempNext;// change head if neededif(k==1)head=y;if(k==n)head=x;returnhead;}// utility to print liststaticvoidprintList(Nodehead){while(head!=null){System.out.print(head.data);if(head.next!=null)System.out.print(" -> ");head=head.next;}System.out.println();}publicstaticvoidmain(String[]args){Nodehead=newNode(5);head.next=newNode(10);head.next.next=newNode(8);head.next.next.next=newNode(5);head.next.next.next.next=newNode(9);head.next.next.next.next.next=newNode(3);intk=2;head=swapKth(head,k);printList(head);}}
Python
# Node class for singly linked listclassNode:def__init__(self,d):self.data=dself.next=NonedefswapKth(head,k):ifnothead:returnhead# Count lengthn=0temp=headwhiletemp:n+=1temp=temp.next# if k is more than length, no swapifk>n:returnhead# if kth from start and end are same, no swapif2*k-1==n:returnhead# find kth node from start and its prevprevX=Nonex=headforiinrange(1,k):prevX=xx=x.next# find kth node from end and its prevprevY=Noney=headforiinrange(1,n-k+1):prevY=yy=y.next# adjust previous pointersifprevX:prevX.next=yifprevY:prevY.next=x# swap next pointerstempNext=x.nextx.next=y.nexty.next=tempNext# change head if neededifk==1:head=yifk==n:head=xreturnhead# utility to print listdefprintList(head):whilehead:print(head.data,end="")ifhead.next:print(" -> ",end="")head=head.nextprint()if__name__=="__main__":head=Node(5)head.next=Node(10)head.next.next=Node(8)head.next.next.next=Node(5)head.next.next.next.next=Node(9)head.next.next.next.next.next=Node(3)k=2head=swapKth(head,k)printList(head)
C#
usingSystem;classNode{publicintdata;publicNodenext;publicNode(intd){data=d;next=null;}}classGfG{staticNodeSwapKth(Nodehead,intk){if(head==null)returnhead;// Count lengthintn=0;Nodetemp=head;while(temp!=null){n++;temp=temp.next;}// if k is more than length, no swapif(k>n)returnhead;// if kth from start and end are same, no swapif(2*k-1==n)returnhead;// find kth node from start and its prevNodeprevX=null;Nodex=head;for(inti=1;i<k;i++){prevX=x;x=x.next;}// find kth node from end and its prevNodeprevY=null;Nodey=head;for(inti=1;i<n-k+1;i++){prevY=y;y=y.next;}// adjust previous pointersif(prevX!=null)prevX.next=y;if(prevY!=null)prevY.next=x;// swap next pointersNodetempNext=x.next;x.next=y.next;y.next=tempNext;// change head if neededif(k==1)head=y;if(k==n)head=x;returnhead;}// utility to print liststaticvoidPrintList(Nodehead){while(head!=null){Console.Write(head.data);if(head.next!=null){Console.Write(" -> ");}head=head.next;}Console.WriteLine();}publicstaticvoidMain(string[]args){Nodehead=newNode(5);head.next=newNode(10);head.next.next=newNode(8);head.next.next.next=newNode(5);head.next.next.next.next=newNode(9);head.next.next.next.next.next=newNode(3);intk=2;head=SwapKth(head,k);PrintList(head);}}
JavaScript
// Node class for singly linked listclassNode{constructor(d){this.data=d;this.next=null;}}functionswapKth(head,k){if(!head)returnhead;// Count lengthletn=0;lettemp=head;while(temp){n++;temp=temp.next;}// if k is more than length, no swapif(k>n)returnhead;// if kth from start and end are same, no swapif(2*k-1===n)returnhead;// find kth node from start and its prevletprevX=null;letx=head;for(leti=1;i<k;i++){prevX=x;x=x.next;}// find kth node from end and its prevletprevY=null;lety=head;for(leti=1;i<n-k+1;i++){prevY=y;y=y.next;}// adjust previous pointersif(prevX)prevX.next=y;if(prevY)prevY.next=x;// swap next pointerslettempNext=x.next;x.next=y.next;y.next=tempNext;// change head if neededif(k===1)head=y;if(k===n)head=x;returnhead;}// utility to print listfunctionprintList(head){letres=[];while(head){res.push(head.data);head=head.next;}console.log(res.join(" -> "));}// Driver Codelethead=newNode(5);head.next=newNode(10);head.next.next=newNode(8);head.next.next.next=newNode(5);head.next.next.next.next=newNode(9);head.next.next.next.next.next=newNode(3);letk=2;head=swapKth(head,k);printList(head);