#include <stdio.h>
#include <stdlib.h>
typedef struct Node {
int data;
struct Node* next;
} Node, *LinkedList;
// 创建一个新节点
Node* createNode(int data) {
Node* newNode = (Node*)malloc(sizeof(Node));
if (newNode == NULL) {
printf("Error! Unable to create a new node.\n");
exit(0);
}
newNode->data = data;
newNode->next = NULL;
return newNode;
}
// 在链表末尾添加新节点
void append(LinkedList* head, int data) {
if (*head == NULL) {
*head = createNode(data);
}
else {
Node* lastNode = *head;
while (lastNode->next != NULL) {
lastNode = lastNode->next;
}
lastNode->next = createNode(data);
}
}
// 打印链表
void printList(LinkedList head) {
while (head != NULL) {
printf("%d ", head->data);
head = head->next;
}
printf("\n");
}
LinkedList findNodeK(Node* head1, int k)
{
if (head1 == NULL)
{
return NULL;
}
int length = 0;
Node* tail = head1;
while (tail != NULL)
{
tail = tail->next;
length++;
}
if (length <= k)
{
return head1;
}
Node* cur = head1;
int i = length - k;
while(i != 0)
{
cur = cur->next;
i--;
}
return cur;
}
int main() {
LinkedList head1 = NULL;
append(&head1, 1);
append(&head1, 2);
append(&head1, 3);
append(&head1, 4);
append(&head1, 5);
append(&head1, 6);
printf("Original List1: ");
printList(head1);
LinkedList head = findNodeK(head1, 4);
printf("findNodeK List: ");
printList(head);
system("pause");
return 0;
}
参考:https://blog.csdn.net/weixin_53161762/article/details/137611306?spm=1001.2014.3001.5501