#include<stdio.h> #include<stdlib.h> typedef int ElemType; typedef struct LNode{ ElemType data; struct LNode *next; }LNode,*LinkList; //尾插法 LinkList List_TailInsert(LinkList &L) { ElemType x; L=(LinkList)malloc(sizeof(LNode)); LNode *s,*r=L; printf("请输入单链表各个节点,以9999结束!\n"); scanf("%d",&x); while(x!=9999) { s=(LNode*)malloc(sizeof(LNode)); s->data=x; r->next=s; r=s; scanf("%d",&x); } r->next=NULL; return L; } int Length(LinkList L) { LNode *p=L; int count=0; while(p->next!=NULL) { p=p->next; count++; } return count; } int Search_k(LinkList list,int k){ LinkList p=list->next,q=list->next; int count=0; while(p!=NULL) { if(count<k) { count++; p=p->next; } else { q=q->next; p=p->next; } } if(count<k) return 0; else { printf("倒数第%d个元素是%d\n",k,q->data); return 1; } } int main(){ LinkList L; LinkList R,S;//接收输入数据和处理完的B R=List_TailInsert(L); int a=Search_k(R,3); if(a==1) printf("ok"); else printf("error"); }