您的位置:首页 > 理论基础 > 数据结构算法

数据结构实验之链表九:双向链表

2020-02-03 07:07 661 查看

数据结构实验之链表九:双向链表
Time Limit: 1000 ms Memory Limit: 65536 KiB

Problem Description
学会了单向链表,我们又多了一种解决问题的能力,单链表利用一个指针就能在内存中找到下一个位置,这是一个不会轻易断裂的链。但单链表有一个弱点——不能回指。比如在链表中有两个节点A,B,他们的关系是B是A的后继,A指向了B,便能轻易经A找到B,但从B却不能找到A。一个简单的想法便能轻易解决这个问题——建立双向链表。在双向链表中,A有一个指针指向了节点B,同时,B又有一个指向A的指针。这样不仅能从链表头节点的位置遍历整个链表所有节点,也能从链表尾节点开始遍历所有节点。对于给定的一列数据,按照给定的顺序建立双向链表,按照关键字找到相应节点,输出此节点的前驱节点关键字及后继节点关键字。

Input
第一行两个正整数n(代表节点个数),m(代表要找的关键字的个数)。第二行是n个数(n个数没有重复),利用这n个数建立双向链表。接下来有m个关键字,每个占一行。

Output
对给定的每个关键字,输出此关键字前驱节点关键字和后继节点关键字。如果给定的关键字没有前驱或者后继,则不输出。
注意:每个给定关键字的输出占一行。
一行输出的数据之间有一个空格,行首、行末无空格。

Sample Input
10 3
1 2 3 4 5 6 7 8 9 0
3
5
0
Sample Output
2 4
4 6
9
Hint

Source

错误代码:
#include <stdio.h>
#include <stdlib.h>
struct node
{
int data;
struct node *next;
struct node *next1;
};
int main()
{
int n,m,k;
struct node *head,*p,*q;
head=(struct node *)malloc(sizeof(struct node));
head->next=NULL;
head->next1=NULL;
scanf("%d %d",&n,&m);
p=head;
while(n–)
{
q=(struct node *)malloc(sizeof(struct node));
q->next=NULL;
q->next1=NULL;
scanf("%d",&q->data);
p->next=q;
q->next1=p;
p=p->next;
}
while(m–)
{
scanf("%d",&k);
q=head->next;
while(q)
{
if(q->data==k)
break;
q=q->next;
}
p=q;
if(p->next1!=NULL)
{
p=p->next1;
printf("%d",p->data);
}
if(q->next!=NULL)
{
q=q->next;
printf(" %d",q->data);
}
printf("\n");
}
return 0;
}

这回直接wa,程序运行中没有崩还不错吧!!嘿嘿。
没有找出错误。。。

找出错误,不会改。(如果第一个是空,就是p指向了空的那么就会输出一个空格加上q->data,输出的格式就错了。)需要用判断语句,判断三种情况。

啊哈,凭着我的聪明才智,终于想出来了,原来我的判断是出问题了。

正确代码:
#include <stdio.h>
#include <stdlib.h>
struct node
{
int data;
struct node *next;
struct node *next1;
};
int main()
{
int n,m,k;
struct node *head,*p,*q;
head=(struct node *)malloc(sizeof(struct node));
head->next=NULL;
head->next1=NULL;
scanf("%d %d",&n,&m);
p=head;
while(n–)
{
q=(struct node *)malloc(sizeof(struct node));
q->next=NULL;
q->next1=NULL;
scanf("%d",&q->data);
p->next=q;
q->next1=p;
p=p->next;
}
while(m–)
{
scanf("%d",&k);
q=head->next;
while(q)
{
if(q->datak)
break;
q=q->next;
}
p=q;
q=q->next;
p=p->next1;
if(p!=head&&q!=NULL)
{
printf("%d %d\n",p->data,q->data);
}
else if(p!=head&&qNULL)
{
printf("%d\n",p->data);
}
else if(p==head&&q!=NULL)
{
printf("%d\n",q->data);
}
}
return 0;
}

  • 点赞
  • 收藏
  • 分享
  • 文章举报
qq_32639797 发布了12 篇原创文章 · 获赞 0 · 访问量 55 私信 关注
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: