问题 C: DS双向链表—前驱后继

问题 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;
}
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值