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

来源:互联网 发布:无人机航线保持算法 编辑:程序博客网 时间:2024/05/21 14:00

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

Time Limit: 1000ms   Memory limit: 65536K  有疑问?点这里^_^

题目描述

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

输入

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

输出

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

 

示例输入

10 31 2 3 4 5 6 7 8 9 0350

示例输出

2 44 69

提示


来源


view plaincopyprint如果您复制代码时出现行号,请点击左边的“view plain”后再复制
  1. #include <stdio.h>  
  2. #include <stdlib.h>  
  3. struct node  
  4. {  
  5.     int data;  
  6.     struct node *next;  
  7. } ;  
  8. struct node *creat(int n)  
  9. {  
  10.     int i;  
  11.     struct node *head,*p,*tail;  
  12.     head=(struct node *)malloc(sizeof(struct node));  
  13.     head->next=NULL;  
  14.     tail=head;  
  15.     for(i=0; i<n; i++)  
  16.     {  
  17.         p=(struct node *)malloc(sizeof(struct node));  
  18.         scanf("%d",&p->data);  
  19.         p->next=NULL;  
  20.         tail->next=p;  
  21.         tail=p;  
  22.     }  
  23.     return head;  
  24. };  
  25. struct node *found(struct node *head,int k)  
  26. {  
  27.     struct node *p,*q;  
  28.     p=head->next;  
  29.     q=head;  
  30.     while(p->next!=NULL)  
  31.     {  
  32.         if(p->data==k)  
  33.         {  
  34.             if(q==head)  
  35.                 printf("%d\n",p->next->data);  
  36.             else  
  37.                 printf("%d %d\n",q->data,p->next->data);  
  38.             break;  
  39.         }  
  40.         q=p;  
  41.         p=p->next;  
  42.     }  
  43.     if(p->next==NULL)  
  44.         printf("%d\n",q->data);  
  45.         return NULL;  
  46. };  
  47. int main()  
  48. {  
  49.     int key,n,m,i;  
  50.     struct node *head;  
  51.     scanf("%d %d",&n,&m);  
  52.     head=creat(n);  
  53.     for(i=0; i<m; i++)  
  54.     {  
  55.         scanf("%d",&key);  
  56.         found(head,key);  
  57.     }  
  58.         return 0;  
  59. }  
  60.    
  61.   
  62.   
例程序


0 0