+ Reply to Thread
Results 1 to 2 of 2

Thread: Find kth node from last in a linked list

  1. #1
    Surfer is offline Senior Member
    Join Date
    Mar 2010
    Posts
    321

    Find kth node from last in a linked list

    Find kth node from last last of a singly linked list.

  2. #2
    Pradeep Panwar is offline Junior Member
    Join Date
    Nov 2010
    Posts
    4
    Suppose one needs to get to the 6th node from the end in this LL. First, just keep on incrementing the first pointer (ptr1) till the number of increments cross n (which is 6 in this case)
    STEP 1 : 1(ptr1,ptr2) -> 2 -> 3 -> 4 -> 5 -> 6 -> 7 -> 8 -> 9 -> 10
    STEP 2 : 1(ptr2) -> 2 -> 3 -> 4 -> 5 -> 6(ptr1) -> 7 -> 8 -> 9 -> 10
    Now, start the second pointer (ptr2) and keep on incrementing it till the first pointer (ptr1) reaches the end of the LL.
    STEP 3 : 1 -> 2 -> 3 -> 4(ptr2) -> 5 -> 6 -> 7 -> 8 -> 9 -> 10 (ptr1)
    So here you have!, the 6th node from the end pointed to by ptr2!
    mynode * nthNode(mynode *head, int n /*pass 0 for last node*/)
    {
    mynode *ptr1,*ptr2;
    int count;
    if(!head)
    {
    return(NULL);
    }
    ptr1 = head;
    ptr2 = head;
    count = 0;
    while(count < n)
    {
    count++;
    if((ptr1=ptr1->next)==NULL)
    {
    //Length of the linked list less than n. Error.
    return(NULL);
    }
    }
    while((ptr1=ptr1->next)!=NULL)
    {
    ptr2=ptr2->next;
    }
    return(ptr2);
    }

+ Reply to Thread

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Similar Threads

  1. Given a node in a binary tree, find the next largest node.
    By yuzi in forum Algorithm/Data Structure Questions
    Replies: 1
    Last Post: 25th June 2010, 20:37
  2. Delete alternate node from a Linked List
    By TopGun in forum Amazon
    Replies: 0
    Last Post: 30th May 2008, 11:56
  3. Find nth Node from end in a Linked List
    By TopGun in forum Linked Lists
    Replies: 0
    Last Post: 17th February 2008, 23:05

Tags for this Thread

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts