王道数据结构链表算法题第二十二题

在这里插入图片描述

#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <math.h>
#include <time.h>
#include <Windows.h>

typedef struct node
{
	int data;
	struct node* next;
}SingleList;

//初始化
SingleList* init_SingleList()
{
	SingleList* singleList = malloc(sizeof(singleList));
	if (singleList == NULL)
	{
		return NULL;
	}
	singleList->data = 0;
	singleList->next = NULL;

	return singleList;
}

//尾插法创建单链表
void create_SingleList(SingleList* singleList)
{
	SingleList* list, * pmove, * pcreate;
	int data, len;
	list = (SingleList*)malloc(sizeof(SingleList));
	list = singleList;
	if (list == NULL)
		return;
	else
		list->next = NULL;
	pmove = list;
	printf("请输入要创建的单链表的长度:");
	scanf_s("%d", &len);
	printf("请输入数据:");
	for (int i = 0; i < len; i++)
	{
		scanf_s("%d", &data);
		pcreate = (SingleList*)malloc(sizeof(SingleList));
		if (pcreate == NULL)
			return;
		pcreate->data = data;
		pcreate->next = NULL;
		//插入操作
		pmove->next = pcreate;
		pmove = pcreate;
	}
}

//求链表的长度
int len(SingleList* singleList)
{
	SingleList* pmove;
	int count = 0;
	pmove = singleList->next;
	while (pmove != NULL)
	{
		count++;
		pmove = pmove->next;
	}
	return count;
}

//算法1:找倒数第k个结点,即找链表正数第(链表长度 - k + 1)的位置
SingleList* findLocationFrom_SingleList(SingleList* singleList,int location)
{
	SingleList* pmove;
	pmove = singleList->next;
	if (location<0 || location>len(singleList))//判断位置是否合法
		return NULL;
	for (int i = 0; i < len(singleList) - location; i++)//找正数第len(singleList) - location + 1的位置
	{
		pmove = pmove->next;
	}
	
	return pmove;
}

//算法2:使用快慢指针法:先让快指针走k个位置,然后快慢指针在同时走
SingleList* kthToLast(SingleList* list,int k)
{
	SingleList* slow, * fast;
	slow = fast = list->next;
	while (k--)//先让fast指针走k个位置
	{
		if (fast == NULL)
			return NULL;
		fast = fast->next;
	}
	//快慢指针同时走
	while (fast != NULL)
	{
		slow = slow->next;
		fast = fast->next;
	}
	return slow;
}

void printf_SingleList1(SingleList* list)
{
	SingleList* pmove;
	pmove = list->next;
	while (pmove != NULL)
	{
		printf("%d ", pmove->data);
		pmove = pmove->next;
	}
	printf("\n");
}

int main(void)
{
	SingleList* singleList, * p, * flag;
	int location;
	singleList = init_SingleList();
	create_SingleList(singleList);
	printf("初始链表为:\n");
	printf_SingleList1(singleList);

	printf("请输入要查找的位置:");
	scanf_s("%d", &location);
	flag = findLocationFrom_SingleList(singleList, location);
	if (flag != NULL)
		printf("查找成功,链表中倒数第%d个元素的值为:%d\n", location, flag->data);
	else
		printf("查找失败!\n");

	if (p = kthToLast(singleList, location))
	{
		printf("查找成功,链表中倒数第%d个元素的值为:%d\n", location, p->data);
	}
	else
	{
		printf("查找失败!\n");
	}

	system("pause");
	return EXIT_SUCCESS;
}

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值