#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;
}