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)
Time Complexity : O(n)
Space Complexity: O(1)
Please let me know if you have any questions .
No comments:
Post a Comment