Wednesday, April 17, 2013

C Program to swap kth node from first and kth node from last in a Linked List

Consider you have the following linked list and you want to swap second node from first and second node from last .

The steps are given below .

     1)Get the size of the linked list . If the size is less than k you can't swap the element . And in the above linked list if k value is 3 you dont need to swap the element .
     2)The two pointers kthnodefromfirst and kthnodefromlast used to point the nodes that we need to swap and its previous nodes are pointed using previous1,previous2.
     3)swap the two nodes . And while swapping you need to check whether you are swapping the head or not . Its one of the important test case .

Code:(in C)
//Swap kth node from first and last
struct node * swapKthNode(struct node * head,int k)
{
if(head==null)
return null;
int size=size_of_linkedlist(struct node* head);
if(size<k || k==size-k+1)
return head;
int i=k,j=size-k+1;
if(i<j)
head=swap(head,i,j);
else
head=swap(head,j,i);
return head;
}
struct node * swap(struct node * head,int i,int j)
{
struct node* kthnodefromfirst=head,kthnodefromlast,previous1=null,previous2,temp;
while(--i > 0)
{
previous1=kthnodefromfirst;
kthnodefromfirst=kthnodefromfirst->link;
}
j=j-i;
kthnodefromlast=kthnodefromfirst;
while(j-- > 0)
{
previous2=kthnodefromlast;
kthnodefromlast=kthnodefromlast->link;
}
//swap the two nodes
temp=kthnodefromfirst->link
kthnodefromfirst->link=kthnodefromlast->link;
kthnodefromlast->link=temp;
previous2->link=kthnodefromfirst;
if(previous1==null)
head=kthnodefromlast;
else
previous1->link=kthnodefromlast;
return head;
}
view raw swapkth.c hosted with ❤ by GitHub

Time Complexity : O(n)
Space Complexity: O(1)

Please let me know if you have any questions .

No comments: