数据结构实验之链表九:双向链表
来源:互联网 发布:nginx反向代理设置 编辑:程序博客网 时间:2024/05/21 14:43
Problem Description
学会了单向链表,我们又多了一种解决问题的能力,单链表利用一个指针就能在内存中找到下一个位置,这是一个不会轻易断裂的链。但单链表有一个弱点——不能回指。比如在链表中有两个节点A,B,他们的关系是B是A的后继,A指向了B,便能轻易经A找到B,但从B却不能找到A。一个简单的想法便能轻易解决这个问题——建立双向链表。在双向链表中,A有一个指针指向了节点B,同时,B又有一个指向A的指针。这样不仅能从链表头节点的位置遍历整个链表所有节点,也能从链表尾节点开始遍历所有节点。对于给定的一列数据,按照给定的顺序建立双向链表,按照关键字找到相应节点,输出此节点的前驱节点关键字及后继节点关键字。
Input
第一行两个正整数n(代表节点个数),m(代表要找的关键字的个数)。第二行是n个数(n个数没有重复),利用这n个数建立双向链表。接下来有m个关键字,每个占一行。
Output
对给定的每个关键字,输出此关键字前驱节点关键字和后继节点关键字。如果给定的关键字没有前驱或者后继,则不输出。
注意:每个给定关键字的输出占一行。
一行输出的数据之间有一个空格,行首、行末无空格。
Example Input
10 3
1 2 3 4 5 6 7 8 9 0
3
5
0
Example Output
2 4
4 6
9
#include <stdio.h>
#include <stdlib.h>
struct node
{
struct node *next,*first;
int data;
}*head,*tail,*p;
int main()
{
int m,n,i,j,k;
head=(struct node *)malloc(sizeof(struct node));
head->next=NULL;
tail=head;
scanf("%d%d",&n,&m);
for(i=1;i<=n;i++)
{
p=(struct node *)malloc(sizeof(struct node));
p->next=NULL;
scanf("%d",&p->data);
p->first=tail;
p->next=tail->next;
tail->next=p;
tail=p;
}
p=head->next;
for(i=1;i<=m;i++)
{
scanf("%d",&k);
p=head->next;
while(p)
{
if(p->data==k)
{
if(p->first!=head&&p->next!=NULL)
{
printf("%d %d\n",p->first->data,p->next->data);
break;
}
else if(p->first!=head&&p->next==NULL)
{
printf("%d\n",p->first->data);
break;
}
else if(p->next!=NULL&&p->first==head)
{
printf("%d\n",p->next->data);
break;
}
}
p=p->next;
}
}
return 0;
}
#include<bits/stdc++.h>
using namespace std;
struct node
{
struct node *next,*first;
int data;
}*head,*tail,*p;
int n,m;
node *create(int n)
{
head=new node;
head->next=NULL;
tail=head;
for(int i=1;i<=n;i++)
{
p=new node;
scanf("%d",&p->data);
p->first=tail;
// p->next=tail->next;
tail->next=p;
tail=p;
}
return head;
}
void print(node *head,int m)
{
// p=head->next;
int k;
for(int i=1;i<=m;i++)
{
cin>>k;
p=head->next;
while(p)
{
if(p->data==k)
{
if(p->first&&p->next)
{
cout<<p->first->data<<" "<<p->next->data<<endl;
break;
}
else if(p->first)
{
cout<<p->first->data<<endl;
break;
}
else if(p->next)
{
cout<<p->next->data<<endl;
break;
}
}
p=p->next;
}
}
}
int main()
{
cin>>n>>m;
node *head;
head=create(n);
print(head,m);
return 0;
}
- 数据结构实验之链表九:双向链表
- 数据结构实验之链表九:双向链表
- 数据结构实验之链表九:双向链表
- 数据结构实验之链表九:双向链表
- 数据结构实验之链表九:双向链表
- 数据结构实验之链表九:双向链表
- 数据结构实验之链表九:双向链表
- 数据结构实验之链表九:双向链表
- 数据结构实验之链表九:双向链表
- 数据结构实验之链表九:双向链表
- 数据结构实验之链表九:双向链表
- 数据结构实验之链表九:双向链表
- 数据结构实验之链表九:双向链表
- 数据结构实验之链表九:双向链表
- 数据结构实验之链表九:双向链表
- 数据结构实验之链表九:双向链表
- 数据结构实验之链表九:双向链表
- 数据结构实验之链表九:双向链表
- python安装及配置
- 用js编写生成指定范围内的随机数
- 一次写代码活动
- 静态库与动态库
- 静态变量
- 数据结构实验之链表九:双向链表
- 平衡二叉树
- Windows下单机安装Spark开发环境
- 八大排序算法
- redis-trib.rb无法执行
- iOS 网络编程 (三)NSURLConnection使用
- 如何查看端口(3306)被那个程序占用?
- 合并两个排序的链表
- 知识目录