/*已知一个带有表头结点的单链表,结点结构为data、link。假设该链表只给出了头指针list。在不改变链表的前提下
,请设计一个尽可能高效的算法,查找链表中倒数第k个位置上的结点(k为正整数)。若查找成功,算法输出该结点的data域
值,并返回1;否则,只返回0。*/
#include<stdio.h>
#include<stdlib.h>
typedef int ElemType;
typedef struct LNode{
ElemType data;
struct LNode *link;
}LNode,*LinkList;
LinkList tailInsertList(LinkList &L)
{
ElemType x;
L = (LinkList)malloc(sizeof(LNode));
LNode *r=L;
scanf("%d",&x);
while(x!=9999)
{
LNode *s = (LNode*)malloc(sizeof(LNode));
s->data = x;
r->link = s;
r = s;
scanf("%d",&x);
}
r->link = NULL;
return L;
}
ElemType findK(LinkList L,int k)
{
LNode *q = L->link;
LNode *p = L->link;
int count = 0;
while(p)
{
if(count<k) ++count;
else
q = q->link;
p = p->link;
}
if(count<k)
return 0;
else{
printf("%d",q->data);
printf("\n");
return 1;
}
}
bool printList(LinkList L)
{
LNode *p = L->link;
while(p)
{
printf("%d ",p->data);
p = p->link;
}
printf("\n");
return true;
}
void main()
{
LinkList L;
tailInsertList(L);
printList(L);
findK(L,3);
}