问题 C: DS双向链表—前驱后继
时间限制: 1 Sec 内存限制: 128 MB
题目描述
在双向链表中,A有一个指针指向了后继节点B,同时,B又有一个指向前驱节点A的指针。这样不仅能从链表头节点的位置遍历整个链表所有节点,也能从链表尾节点开始遍历所有节点。
对于给定的一列数据,按照给定的顺序建立双向链表,按照关键字找到相应节点,输出此节点的前驱节点关键字及后继节点关键字。
输入
第一行两个正整数n(代表节点个数),m(代表要找的关键字的个数)。
接下来输入n个整数为关键字key(数据保证关键字在数列中没有重复)。
接下来有m个要查找的关键字,每个占一行。
输出
对给定的每个关键字,输出此关键字前驱节点关键字和后继节点关键字。如果给定的关键字没有前驱或者后继,则不输出。给定关键字为每个输出占一行。
样例输入
10 3
1 2 3 4 5 6 7 8 9 0
3
1
0
样例输出
2 4
2
9
#include<iostream>
#include<algorithm>
#include<cmath>
#include<string>
#include<map>
using namespace std;
class List
{
public:
int number;
List* next;
List* pre;
List()
{
pre = NULL;
next = NULL;
}
};
class NList {
List* head;
int len;
public:
NList()
{
head = new List();
}
~NList()
{
List* p, * q;
p = head;
while (p->next)
{
q = p->next;
delete p;
p = q;
}
delete p;
}
void insert(int item)
{
List* pre = NULL, * cur = NULL, * now = NULL;
cur = head;
now = new List();
now->number = item;
now->next = NULL;
while (cur->next != NULL)
{
pre = cur;
cur = cur->next;
}
if (cur == head)
{
cur->next = now;
}
else
{
cur->next = now;
now->pre = cur;
}
len++;
}
void display()
{
List* cur;
cur = head->next;
while (cur)
{
cout << " " << cur->number;
cur = cur->next;
}
cout << endl;
}
void fin(int item)
{
List* cur;
cur = head->next;
while (cur)
{
if (cur->number == item)break;
cur = cur->next;
}
if (cur->pre != NULL)
{
cout << cur->pre->number << " ";
}
if (cur->next != NULL)
{
cout << cur->next->number;
}
cout << endl;
}
};
int main()
{
NList p;
int n, number,times;
cin >> n>>times;
for (int i = 0; i < n; ++i)
{
cin >> number;
p.insert(number);
}
//p.display();
for (int i = 0; i < times; ++i)
{
int item;
cin >> item;
p.fin(item);
}
return 0;
}