輸入一個單向鏈表,輸出該鏈表中倒數第k個結點

題目:輸入一個單向鏈表,輸出該鏈表中倒數第k個結點。鏈表的倒數第0個結點爲鏈表的尾指針。



#include "stdio.h"
#include "stdlib.h"

typedef struct LNode{

	int data;
	struct LNode *next;
}LNode;


void CreateListR(LNode *&C, int a[], int n){
	
	LNode *s, *r;

	C = (LNode *)malloc(sizeof(LNode));
	C ->next = NULL;
	
	r = C;

	for(int i=0; i<n; ++i){
		s = (LNode *)malloc(sizeof(LNode));
		s->data = a[i];

		r->next = s;
		r = r->next;
	}

	r->next = NULL;

}


void PrintList(LNode *head){
	
	while(head->next != NULL){
		head = head->next;
		printf("%d ", head->data);
	
	}
	
	putchar('\n');

}



LNode *FindLastKNode(LNode *p, int k){

	LNode *f, *l;

	f = l = p->next;
	
	int n = k-1;
	while(n > 0){
		--n;
		f = f->next;

		if(f == NULL){
			printf("The param 'k' is larger than length of LinkedList.");
			return NULL;
		}
	}

	
	while(f->next != NULL){
		f = f->next;
		l = l->next;
	}

	return l;

}
 
void main(){

	int R[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};

	LNode *head;
	CreateListR(head, R, 10);
	
	LNode *l;
	int k = 4;
	l = FindLastKNode(head, 3);

	printf("%d \n", l->data);

}	


發佈了34 篇原創文章 · 獲贊 4 · 訪問量 10萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章