你的位置:首页 > 信息动态 > 新闻中心
信息动态
联系我们

对带头节的链表,返回倒数第K个节点指针。若表长小于K,返回NULL。要求只能遍历一次链表。(C语言)

2021/12/26 8:17:54
#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;
}