//求单链表中的倒数第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);
}