C (1094) : DS双向链表—前驱后继

Description

在双向链表中,A有一个指针指向了后继节点B,同时,B又有一个指向前驱节点A的指针。这样不仅能从链表头节点的位置遍历整个链表所有节点,也能从链表尾节点开始遍历所有节点。

对于给定的一列数据,按照给定的顺序建立双向链表,按照关键字找到相应节点,输出此节点的前驱节点关键字及后继节点关键字。

Input

第一行两个正整数n(代表节点个数),m(代表要找的关键字的个数)。

接下来输入n个整数为关键字key(数据保证关键字在数列中没有重复)。

接下来有m个要查找的关键字,每个占一行。

Output

对给定的每个关键字,输出此关键字前驱节点关键字和后继节点关键字。如果给定的关键字没有前驱或者后继,则不输出。给定关键字为每个输出占一行。

Sample

AC代码:

cpp 复制代码
#include <iostream>
using namespace std;
typedef struct DNode{
	int data;
	struct DNode* pr, * next;
}DNode,*DLinkList;

void InitList(DLinkList& L){
	L = (DNode*)malloc(sizeof(DLinkList));
	L->pr = NULL;
	L->next = NULL;
}

//尾插法
DLinkList TailInsert(DLinkList& L, int t) {
	InitList(L);
	DNode* s, * r = L;
	int x;
	while (t--) {
		cin >> x;
		s = (DNode*)malloc(sizeof(DNode));
		s->data = x;
		s->next = NULL;
		s->pr = r;
		r->next = s;
		r = s;
	}
	return L;
}
//请勿复制粘贴,答案仅供参考
void search(DLinkList& L,int x) {
	DNode* p = L->next;
	while (true)
	{
		if (p == NULL) {
			break;
		}
		if (p->data == x && p->pr->pr != NULL && p->next != NULL) {
			cout << p->pr->data << " " << p->next->data << endl;
			return;
		}
		else if (p->data == x && p->pr->pr == NULL && p->next != NULL)
		{
			cout << p->next->data << endl;
			return;
		}
		else if (p->data == x && p->pr->pr != NULL && p->next == NULL)
		{
			cout << p->pr->data << endl;
			return;
		}
		p = p->next;
	}
}


int main() {
	int data, num, times, x;
	cin >> num >> times;
	DLinkList L = TailInsert(L,num);
	while (times--) {
		cin >> x;
		search(L, x);
	}
	return 0;
}
相关推荐
apcipot_rain1 小时前
C++转Java日记(04)
java·开发语言·c++
wuyk5551 小时前
Keil工具链-第05讲-启动文件与__main到底做了什么
c语言·stm32·单片机·嵌入式硬件·物联网
NEFU_Jyj1 小时前
牛客周赛R168
算法
云和数据.ChenGuang2 小时前
LangGraph 异步 Node 的设计与写法实践
开发语言·人工智能·python·机器学习·php
WL学习笔记3 小时前
vector模拟实现
c++
蜗牛一步步往上爬5 小时前
第十六章 C++语言在深度学习中的应用
开发语言·c++·深度学习
张张123y7 小时前
DSH 插件调试避坑:client.js 设置面板、热重载与高频报错排查表
开发语言·javascript·人工智能·开源·ecmascript·后端开发·ai agent
likexuec8 小时前
数据结构(2)
数据结构
Navigator_Z9 小时前
LeetCode //C - 1317. Convert Integer to the Sum of Two No-Zero Integers
c语言·算法·leetcode