题目
设计一个函数,在带附加头结点的单链表中查找倒数第k个结点。若查找成功,函数通过参数表送出该结点的data域的
值,并返回rue,否则只返回 false;在主函数中,调用该数并查找倒数第4个结点的值,如果查找成功,则输出查找
到的值(加一个回车),否则什么都不输出。
主要思想
- 定义两个工作指针p和q ;
- 先让p进行移动直到正数第K个数 ;
- 然后q指针开始跟随p指针一起移动 ;
- 直至“”p“”指针遍历到链表末尾 ;
- 此时“”q“”指针指的就是倒数第k个数
c++源代码
#include<iostream>
#include<bits/stdc++.h>
using namespace std;
struct Node {
int data;
Node *next;
};
class List {
private:
Node *first;
public:
List();
~List();
void Insert(int x);
bool SearchK(int k);
};
List::List()
{
first = new Node();
first->next = NULL;
}
List::~List()
{
}
void List::Insert(int x)//插入元素
{
Node *temp = first;
while (temp->next!=NULL)
temp = temp->next;
Node *n = new Node();
n->data = x;
n->next = NULL;
temp->next = n;
}
//write your code here
bool List::SearchK(int k)
{
Node *p=first;
Node *q=first;
int n=0;
while(n<k)//p自己动
{n++;
p=p->next;
}
while(p!=NULL)//p,q一起移动
{
p=p->next;
q=q->next;
}
printf("%d",q->data);
return true;
}
int main()
{
List l;
int i;
cin >> i;
while (i!=-1) {
l.Insert(i);
cin >> i;
}
//write your code here
l.SearchK(4);
return 0;
}