目录
返回倒数第k个节点
输入一个链表,输出该链表中倒数第k个结点。
示例:
输入:1,{1,2,3,4,5} 返回值:{5}
思路
思路1:遍历链表得到节点数量listNum,返回第listNum-k-1个节点。
思路2:快慢节点,fast和slow中间相差k步(
或k-1步)
完整代码
#define _CRT_SECURE_NO_WARNINGS 1
// 输入一个链表,输出该链表中倒数第k个结点。
#include<stdio.h>
#include<stdlib.h>
typedef struct SList
{
int val;
struct SList* next;
}SLTNode;
SLTNode* createlist(int* arr, int z)
{
SLTNode* head = NULL;
SLTNode* tail = NULL;
for (int i = 0; i < z; i++)
{
SLTNode* newnode = (SLTNode*)malloc(sizeof(struct SList));
if (newnode == NULL)
{
perror("malloc fail");
exit(-1);
}
else
{
newnode->val = *(arr + i);
newnode->next = NULL;
}
if (head == NULL)
{
head = newnode;
tail = newnode;
}
else
{
tail->next = newnode;
tail = newnode;
}
}
return head;
}
void SLTPrint(SLTNode* head)
{
SLTNode* cur = head;
while (cur)
{
printf("%d->", cur->val);
cur = cur->next;
}
printf("NULL\n");
}
SLTNode* FindKthToTail(SLTNode* head, int k)
{
int listNum = 0;
SLTNode* cur = head;
while (cur)
{
listNum++;
cur = cur->next;
}
// printf("%d\n", listNum);
cur = head;
if (listNum < k)
return NULL;
for (int i = listNum - k; i > 0; i--)
{
cur = cur->next;
}
return cur;
}
void test2()
{
// 通过数组初始化单链表
int arr[] = { 1, 2, 3, 4, 5, 6, 7 };
SLTNode* plist = createlist(arr, sizeof(arr) / sizeof(arr[0]));
SLTPrint(plist);
// 返回倒数第 k 个节点
int k = 6;
SLTNode* kthatil = FindKthToTail(plist, k);
SLTPrint(kthatil);
}
int main()
{
// 返回倒数第 k 个节点
test2();
return 0;
}