【算法】【求链表中的倒数第K个元素】

在程序的鲁棒性上,我对链表的长度没有考虑在内

#include <stdio.h>
#include <error.h>
#include <math.h>
#include <stdlib.h>
#include <time.h>
 
#define ERROR  -22
 
#define DEBUG	0

typedef struct single_node *Node;

struct single_node{
	int element;
	struct single_node *next;
};

static Node CreateLine(Node ahead, int element)
{
	if(ahead==NULL)
		return NULL;
	
	Node node = NULL;
	node = (Node)malloc(sizeof(*node));
	if(node==NULL){
		fprintf(stderr, "%s: there is no space\n", __func__);
		return NULL;
	}
	node->element = element;
	node->next = NULL;
	ahead->next = node;
	return node;
}

static int PrintLine(Node head, int *num)
{
	Node node = head;
	int i = 0;
	if(head==NULL)
		return ERROR;
	while(node){
		printf("%d\t", node->element);
		node = node->next;
		i++;
	}
	printf("\n");
	*num = i;
	return 0;
}

static int get_rand()
{
	int num = 0;
	num = 1+(rand()%100);
	return num;
}


static Node FindLastK(Node head, int k,  int *num)
{
	Node node = head;
	Node ptr = head;
	
	
	if(k<=0){
		fprintf(stderr, "k should not be zero");
		return NULL;
	}
	
	if(head==NULL){
		fprintf(stderr, "head should not be NULL\n");
		return NULL;
	}
	
	//还有就是k是大于链表的长度的,这个是我考虑的疏忽点
	if(k>*num){
		fprintf(stderr, "invalid k:%d should not large than %d\n", k, num);
		return NULL;
	}
	
	int count = 0;
	while(node){
		count++;
		if(count>k){
			ptr = ptr->next;
		}
		node = node->next;
		if(node==NULL){
			return ptr;
		}
	}
	return NULL;
}

int main()
{ 
	Node head = NULL;
	Node node = NULL;
	int element = 0;
	srand(time(NULL));
	#if DEBUG
	printf("%d\n", sizeof(*head));
	printf("%d\n", sizeof(struct single_node));
	#endif
	
	head = (Node)malloc(sizeof(*head));
	if(head==NULL){
		fprintf(stderr, "%s: there is no space\n", __func__);
		return ERROR;
	}
	element = get_rand();
	if(element>100||element<1){
		return ERROR;
	}
	head->element = element;
	node = head;
	int i = 1;
	while(i<10){
		element = get_rand();
		if(element>100||element<1){
			return ERROR;
		}
		node = CreateLine(node, element);
		i++;
	}
	int num = 0;
	PrintLine(head, &num);
	
	// 实际上k的值可以通过char转int来判断输入的合法性
	Node node_k = FindLastK(head, 1, &num);
	if(node_k!=NULL){
		printf("%d\n", node_k->element);
	}
	return 0;
}

猜你喜欢

转载自blog.csdn.net/feifei_csdn/article/details/81192169