求链式线性表的倒数第K项

利用双指针进行移动,将一个指针先移动K个位置,当这个指针最后移动到尾部时,另外一个指针正好直到倒数第k项

#include<stdio.h>
#include<stdlib.h>
 
typedef struct node *ptrNode;
typedef ptrNode LinkList;  //头结点
typedef ptrNode Position;//中间节点
typedef int ElementType;
struct node{
	ElementType Element;
	Position next;
};
 
LinkList creatList(void)              
{
	LinkList head,r,p;
	int x;
	head = (struct node*)malloc(sizeof(struct node));    
	r = head;
	scanf("%d",&x);
	while(x >= 0){
		p = (struct node*)malloc(sizeof(struct node));
		p->Element = x;
		r->next = p;
		r = p;
		scanf("%d",&x);
	}
	r->next = NULL;
	return head;
}
 
void printLastKth(LinkList L, int k)
{
	Position p, q;
	int i;
 
	p = L;
	q = L;
 
		for(i = 0; i < k; i++){
			p = p->next;
			if(p == NULL)
				break;
		}
		if(p == NULL)
				printf("NULL");
		else{
			while(p != NULL){
				p = p->next;
				q = q->next;
			}
			printf("%d",q->Element);
		}
 
}
 
void destroyLinkList(LinkList L)
{
	LinkList p,q;
	p = L->next;
	while(p){
		q = p->next;
		free(p);
		p = q;
	}
	L = NULL;
}
 
int main()
{
	LinkList L;
	int k;
 
	scanf("%d",&k);
	L = creatList();
 
	printLastKth(L, k);
	
	destroyLinkList(L);
 
	
	return 0;
}

 

点赞