#include<stdio.h>
#include<stdlib.h>
struct Node{
int data;
struct Node *next;
};
void tailInsert(struct Node *head,int num){
struct Node *p,*q;
p=head;
while(p->next!=NULL){
p=p->next;
}
q=(struct Node *)malloc(sizeof(struct Node));
q->data=num;
q->next=p->next;
p->next=q;
}
void show(struct Node *head){
struct Node *p;
p=head->next;
while(p!=NULL){
printf(" %d",p->data);
p=p->next;
}
printf("\n");
}
struct Node *FindK(struct Node *head,int k){/*解决问题的核心代码*/
struct Node *p,*q;
p=head;
q=head;
int i=1;
while(i<k&&q->next!=NULL){
q=q->next;
i++;
}
if(q->next==NULL){
return NULL;
}
while(q->next!=NULL){
q=q->next;
p=p->next;
}
return p;
}
int main(){
struct Node *head,*rev;
head=(struct Node *)malloc(sizeof(struct Node));
head->next=NULL;
for(int i=10;i>=1;i--){
tailInsert(head,i);
}
printf("初始链表:");
show(head);
int k=6;
rev=FindK(head,k);
if(rev==NULL){
printf("NULL.\n");
}else{
printf("倒数第%d个节点值为 %d.",k,rev->data);
}
return 0;
}
