已知一个带有表头结点的单链表,结点结构为 data,link 。假设该链表只给出了头指针list,在不改变链表的前提下,请设计一个尽可能高效的算法,查找链表中倒数第k个位置上的结点(k为正整数)。若查找成功,算法输出该结点的data域的值,并返回1,否则返回0.
// exam.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include<iostream>
#include<string>
#include<stdio.h>
#include<set>
#include<vector>
#include<algorithm>
using namespace std;
typedef int ElemType;
struct LNode {
ElemType data;
LNode * link;
} ;
int search_k(LNode * list, int k) {
LNode *p = list->link, *q = list->link;
int count = 0;
while (p != NULL) {
if (count < k) count++;
else q = q->link;
p = p->link;
}
if (count < k) return 0; //查找失败返回0
else {
printf("%d", q->data);
return 1;
}
}
int main()
{
LNode *node1 = new LNode;
LNode *node2 = new LNode;
LNode *node3 = new LNode;
LNode *node4 = new LNode;
LNode *node5 = new LNode;
node1->data = 5;
node1->link = node2;
node2->data = 3;
node2->link = node3;
node3->data = 6;
node3->link = node4;
node4->data = 1;
node4->link = node5;
node5->data = 2;
node5->link = NULL;
search_k(node1, 1);
return 0;
}