求链表倒数第 k 个结点
输入一个单向链表,输出该链表中倒数第 k 个结点,
链表的倒数第 0 个结点为链表的尾指针。
#include<stdio.h>
#include<assert.h>
typedef struct node {
int data;
struct node *next;
}Lnode;
int initlink(Lnode *a, int *A, int len) {
assert(A);
Lnode *p=NULL;
for (int i = 0; i < len; i++) {
Lnode *t = (int *)malloc(sizeof(Lnode));
t->data = A[i];
if (i == 0)
p = a = t;
else {
p->next = t;
p = p->next;
}
}
p->next = NULL;
return a;
}
int findK(Lnode *a,int k) {
assert(a && k); //若链表为空,k为0
Lnode *p, *q;
p = q = a;
for (int i = 1; i <k; i++) {
if (q->next != NULL) { //结点数少于k
q = q->next;
}
else {
printf("K大于链表长度");
return 0;
}
}
while (q->next != NULL) {
q = q->next;
p = p->next;
}
printf("%d\n", p->data);
}
int main() {
int A[] = { 1,2,3,4,5,6,7,8,9,10,11,12,13 };
int len = sizeof(A) / sizeof(A[0]);
int K = 0;
Lnode *a = NULL;
a=initlink(a, A, len);
findK(a, K);
return 0;
}