首页 > 代码库 > [004] last_k_node

[004] last_k_node

[Description] find the k-th node from the last node of single linked list.

e.g.  Linked-list: 1-2-3-4-5-6-7-8-9

     the last 4th node is: 6

[Thought] using two node point which are separated by k-2 nodes and moving them together.  O(n)

[Implementation] C code:

 1 #include<stdio.h> 2 #include<stdlib.h> 3  4 // construct single linked list. 5 typedef struct node 6 { 7         int data; 8         struct node *next; 9 }linklist, *pLL;10 11 // create a linked list from array.12 pLL createLL(int seq[], int size)13 {14         int i;15         pLL phead,pnode;16 17         if(size>=1)18         {19                 phead=pnode=(pLL)malloc(sizeof(linklist));20                 pnode->next=NULL;21                 pnode->data=http://www.mamicode.com/seq[0];22         }23         else24         {25                 printf("ERROR: No element in array!");26                 return NULL;27         }28 29         for(i=1;i<size;i++)30         {31 32                 pnode->next=(pLL)malloc(sizeof(linklist));33                 pnode=pnode->next;34                 pnode->next=NULL;35                 pnode->data=http://www.mamicode.com/seq[i];36         }37         return phead;38 }39 40 // find the Kth node from the last one.41 int lastKnode(pLL pll,int k)42 {43         linklist *m,*n;44         m=pll;45         int i;46 47         for(i=1;i<k;i++)48         {49                 if(m!=NULL)50                 {51                         m=m->next;52                 }53                 else54                 {55                         printf("ERROR:The length of linklist is less than k!");56                         return -1;57                 }58         }59         n=pll;60 61         while(m->next!=NULL)62         {63                 m=m->next;64                 n=n->next;65         }66         return n->data;67 }68 69 main()70 {71         int seq[]={1,2,3,4,5,6,7,8,9};72         int size;73         pLL pll;74         pll=NULL;75         size=sizeof(seq)/sizeof(seq[0]);76         pll=createLL(seq,size);77 78         int k=3;79         printf("The %dth node from the last is:%d\n",k,lastKnode(pll,k));80 }

 

[004] last_k_node