代码如下
以下是完整代码(不想看的可以忽略)
#include <stdio.h>
#include <stdlib.h>
/************************************/
/* 链表实现的头文件,文件名slnklist.h */
/************************************/
typedef int datatype;
typedef struct link_node{
datatype info;
struct link_node *next;
}node;
/*****************************************************/
/* 函数功能:建立一个空的单链表 */
/* 函数参数:无 */
/* 函数返回值:指向node类型变量的指针 */
/* 文件名:slnklist.c,函数名:init() */
/******************************************************/
node *init() /*建立一个空的单链表*/
{
return NULL;
}
/****************************************************/
/* 函数功能:输出单链表中各个结点的值 */
/* 函数参数:指向node类型变量的指针head */
/* 函数返回值:空 */
/* 文件名slnklist.c,函数名display() */
/*****************************************************/
void display(node *head)
{
node *p;
p=head;
if(!p) printf("单链表是空的!\n");
else
{
printf("单链表各个结点的值为:");
while(p) { printf("%5d",p->info);p=p->next;}
}
printf("\n");
}
//尾插法建立单链表
node *creatlistr(node *head)
{
node *p=head,*r=NULL;
datatype x;
printf("请输入单链表各结点值(用0结束):");
scanf("%d",&x);
while(x)
{
p=(node*)malloc(sizeof(node));
p->info=x;
if(head==NULL)
head=p;
else
r->next=p;
r=p;
scanf("%d",&x);
}
if(r!=NULL)
r->next=NULL;
return head;
}
//查找倒数第n个结点
node *rearfind(node *head)
{
int i,n;
node *pre=head,*p=head;
printf("请输入要查找倒数第几个结点值:");
scanf("%d",&n);
if(n<1)
{
printf("非法输入!");
return NULL;
}
else
{
for(i=0;i<n;i++)
p=p->next;
while(p)
{
pre=pre->next;
p=p->next;
}
return pre;
}
}
void main()
{
node *head=init();
head=creatlistr(head);
display(head);
if(rearfind(head))
printf("找到了,是%d",rearfind(head)->info);
}