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)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//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; | |
} |
Time Complexity : O(n)
Space Complexity: O(1)
Please let me know if you have any questions .
No comments:
Post a Comment