Find kth to last element of a singly linked list.

Implement an algorithm to find the kth to last element of a singly linked list.

C++:
01 Node* kLast(Node* head, int k)
02 {
03     Node* test=head;
04     Node* klast=head;
05     for(int i=0;i<k;i++)
06         test=test->next;
07     while(test){
08         test=test->next;
09         klast=klast->next;
10     }
11     return klast;
12 }
Advertisements
This entry was posted in Array and linked list. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s