首页 » C++ » 带头结点的单链表和不带头结点的单链表的倒数第K个节点

带头结点的单链表和不带头结点的单链表的倒数第K个节点

原文 http://blog.csdn.net/yp18792574062/article/details/75576890

2017-07-20 20:20:05阅读(211)

//求单链表中的倒数第K个节点
#include<stdio.h>
#include<malloc.h>
typedef struct _Node
{
	int val;
	struct _Node* next;
}Node,*LinkList;
//带头结点的单链表
#if 0
void InitList(LinkList* list)
{
	(*list) = (Node*)malloc(sizeof(Node));
	(*list)->next = NULL;
}
void InsertTail(LinkList list)
{
	int data;
	scanf("%d", &data);
	while (data != 0)
	{
		Node* node = (Node*)malloc(sizeof(Node));
		node->val = data;
		node->next = NULL;
		Node* r = list;
		while (r->next != NULL)
		{
			r = r->next;
		}
		r->next = node;
		scanf("%d", &data);
	}
}
void Print(LinkList list)
{
	Node* r = list->next;
	while (r != NULL)
	{
		printf("%d ", r->val);
		r = r->next;
	}
	printf("\n");
}
Node* FindKNode(LinkList list, int k)
{
	if (list == NULL || k < 1)
	{
		return NULL;
	}
	Node* p1 = list->next;
	Node* p2 = list->next;
	while (k > 1 && p1 != NULL)
	{
		k--;
		p1 = p1->next;
	}
	if (p1 == NULL)
	{
		return NULL;
	}
	while (p1->next != NULL)
	{
		p1 = p1->next;
		p2 = p2->next;
	}
	return p2;
}
int main(void)
{
	LinkList list;
	InitList(&list);
	InsertTail(list);
	Node* k = FindKNode(list, 3);
	if (k == NULL)
	{
		printf("not found\n");
	}
	else
	{
		printf("%d\n", k->val);
	}
	Print(list);
}
#endif
//不带头结点的单链表
void InitList(LinkList* list)
{
	(*list) = NULL;
}
void InsertTail(LinkList* list)
{
	int data;
	scanf("%d", &data);
	while (data != 0)
	{
		Node* node = (Node*)malloc(sizeof(Node));
		node->val = data;
		node->next = NULL;
		
		if (*list == NULL)
		{
			*list = node;
		}
		else
		{
			Node* r = *list;
			while (r->next != NULL)
			{
				r = r->next;
			}
			r->next = node;
		}
		
		scanf("%d", &data);
	}
}
void Print(LinkList list)
{
	Node* r = list;
	while (r != NULL)
	{
		printf("%d ", r->val);
		r = r->next;
	}
	printf("\n");
}
Node* FindKNode(LinkList list, int k)
{
	if (list == NULL || k < 1)
	{
		return NULL;
	}
	Node* p1 = list;
	Node* p2 = list;
	while (k > 1 && p1 != NULL)
	{
		k--;
		p1 = p1->next;
	}
	if (p1 == NULL)
	{
		return NULL;
	}
	while (p1->next != NULL)
	{
		p1 = p1->next;
		p2 = p2->next;
	}
	return p2;
}
int main(void)
{
	LinkList list;
	InitList(&list);
	InsertTail(&list);
	Node* k = FindKNode(list, 3);
	if (k == NULL)
	{
		printf("not found\n");
	}
	else
	{
		printf("%d\n", k->val);
	}
	Print(list);
}

最新发布

CentOS专题

关于本站

5ibc.net旗下博客站精品博文小部分原创、大部分从互联网收集整理。尊重作者版权、传播精品博文,让更多编程爱好者知晓!

小提示

按 Ctrl+D 键,
把本文加入收藏夹