You can not traverse the liked list backward unless you have stored it on the stack or at some temporary storage. So if you want to find the kth node from the end without using the temporary storage you will have to adopt different technique.
Consider a link list : 1-> 3 -> 9 -> 23 -> 14 ->NULL
Now 23 is the second last element in the list. To find this element we will use the temp linked list pointer. We will increment that pointer so that it will point to kth position from head. Once the temp pointer is pointing to kth node from head, now increment head and the temp pointer till the temp pointer points to last node of the list.
This ways the the head will point to the kth node from the end. Code below usages the similar technique.
Consider a link list : 1-> 3 -> 9 -> 23 -> 14 ->NULL
Now 23 is the second last element in the list. To find this element we will use the temp linked list pointer. We will increment that pointer so that it will point to kth position from head. Once the temp pointer is pointing to kth node from head, now increment head and the temp pointer till the temp pointer points to last node of the list.
This ways the the head will point to the kth node from the end. Code below usages the similar technique.
struct Node { int data; Node * pNext; };
Node * FindKthNodeFromEnd(Node * pHead, int kthPos)
{ if (pHead) { Node * pTemp = pHead; int i = 1; while (i < kthPos && pTemp) { pTemp = pTemp->pNext; i++; } if (pTemp) { while (pTemp->pNext) { pHead = pHead->pNext; pTemp = pTemp->pNext; } return pHead; } } return NULL; } |
No comments:
Post a Comment