有两种算法可以实现,此处给出效率较高的一种方法。
算法思想
:设置双指针,p1和p2,先让p1指针从头开始遍历k-1个节点,然后让p1继续遍历,p2从头遍历(p1和p2同时遍历),当p1遍历到链表的末尾,此时p2指针所指向的正好是倒数第k个节点。
如:
head–>1–>2–>3–>4–>5–>6–>7–>8–>9–>10–>NULL
其中倒数第0个节点是NULL,倒数第1个节点是10,倒数第10个节点是1
延伸
:
求出一个排序完毕的数组中,相同数目元素出现次数大于100的元素.
这也需要一个窗口机制.即比较a[i] 与a[i+100]两个元素即可.
C语言结构体和指针实现
#include <stdio.h>
#include <stdlib.h>
typedef struct node{
int number;
struct node * next;
}Node;
int getK(Node *link,int k);
int main(){
int n,k,i,temp;
int flag;
printf("Input link's length and countdown element: ");
while(scanf("%d %d",&n,&k)!=EOF && n>=0 && n<=1000 && k>=0 && k<=1000 ){
Node *link = (Node *)malloc(sizeof(Node));
link->next = NULL;
flag = 0;
Node *tail;
tail = link;
printf("Input elements: ");
for(i=0;i<n;i++){
scanf("%d",&temp);
Node *n = (Node *)malloc(sizeof(Node));
n->next = tail->next;
tail->next = n;
tail = tail->next;
n->number = temp;
}
int dataK = getK(link,k);
dataK == -1?printf("NULL\n"):printf("The countdown of %d element: %d\n",k,dataK);
}
return 0;
}
int getK(Node *link,int k){
Node *p1,*p2;
int i;
if(link->next == NULL || k <= 0)
return -1;
p1 = link->next;
for(i=0;i < k-1;i++){ //k-1
if(p1->next == NULL)
return -1;
p1 = p1->next;
}
p2 = link->next;
while(p1->next != NULL){
p1 = p1->next;
p2 = p2->next;
}
return p2->number;
}
运行结果:
输入链表长度为7,查找倒数第3个元素,输入链表可看到返回结果。