由于单链表只能从头到尾依次访问链表的各个节点,所以如果要找链表的倒数第k个元素,也只能从头到尾遍历查找。在查找过程中,设置两个指针,让其中一个指针比另一个指针先移动k步,然后两个指针同时往前移动。循环到先行的指针值为NULL时,另一个指针所指的位置就是要找的位置。
#include <stdio.h>
#include <stdlib.h>
struct Stu{
int data;
struct Stu *next;
};
void printLink(struct Stu *head)
{
struct Stu *p = head;
if(head == NULL){
printf("NULL\n");
exit(-1);
}
while(p != NULL){
printf("%d ",p->data);
p = p->next;
}
printf("\n");
}
struct Stu * creatLink(struct Stu *head)
{
struct Stu *new = head;
while(1){
new = (struct Stu *)malloc(sizeof(struct Stu));
printf("please input your data:\n");
scanf("%d",&(new->data));
if(new->data == 0){
printf("end of input\n");
free(new);
return head;
}
if(head == NULL){
head = new;
}
else{
new->next = head;
head = new;
}
}
}
struct Stu *findNum(struct Stu *head,int k)
{
struct Stu *Ahead = head;
struct Stu *Bhead = head;
int i;
for(i=0;i<k;i++){
Ahead= Ahead->next;
}
while(Ahead != NULL){
Ahead= Ahead->next;
Bhead= Bhead->next;
}
return Bhead;
}
int main()
{
int data;
struct Stu *stuHead = NULL;
stuHead = creatLink(stuHead); //创建链表
printLink(stuHead); //打印链表数据
printf("你想得到倒数第几个节点\n");
scanf("%d",&data);
stuHead = findNum(stuHead,data); //查找倒数第N个节点
printf("倒数的第%d个节点是:%d\n",data,stuHead->data);
return 0;
}