程序员算法之找出链表的第K个结点

View Code
 1 #include <stdio.h>
 2 #include <stdlib.h>
 3 
 4 typedef struct Lode{
 5     int elem;
 6     struct Lode *pnext;
 7 }LNODE, *List;
 8 
 9 /**
10 **创建一个链表
11 **/
12 void CreateList(List &L,int n)
13 {
14     L = (struct Lode*)malloc(sizeof(List));
15     L->pnext = NULL;
16     
17     int num;
18     for(int i = 1;i <= n;i++)
19     {
20         scanf("%d",&num);
21         List p = (struct Lode*)malloc(sizeof(List));
22         p->elem = num;
23         p->pnext = L->pnext;
24         L->pnext = p;    
25     }
26 }
27 
28 List FindK(List L,int k)
29 {
30     List pbegin = L;
31     List pend = L;
32     for(int i= 0;i < k;++i)
33     {
34         if(pbegin->pnext != NULL) pbegin = pbegin->pnext;
35     }
36     while(pbegin->pnext != NULL)
37     {
38         pbegin = pbegin->pnext;
39         pend = pend->pnext;
40     }
41     return pend;
42     
43 }
44 int main()
45 {
46     List L;
47     CreateList(L,10);
48     List ptemp = FindK(L,4);
49     printf("%d",ptemp->elem);
50     return 0;
51 }
一切源于对计算机的热爱
原文地址:https://www.cnblogs.com/liuweilinlin/p/2675704.html