山东理工OJ【2054】双向链表(两种方法)
2014-08-01 08:17
141 查看
双向链表
Time Limit: 1000ms Memory limit: 65536K 有疑问?点这里^_^题目描述
学会了单向链表,我们又多了一种解决问题的能力,单链表利用一个指针就能在内存中找到下一个位置,这是一个不会轻易断裂的链。但单链表有一个弱点——不能回指。比如在链表中有两个节点A,B,他们的关系是B是A的后继,A指向了B,便能轻易经A找到B,但从B却不能找到A。一个简单的想法便能轻易解决这个问题——建立双向链表。在双向链表中,A有一个指针指向了节点B,同时,B又有一个指向A的指针。这样不仅能从链表头节点的位置遍历整个链表所有节点,也能从链表尾节点开始遍历所有节点。对于给定的一列数据,按照给定的顺序建立双向链表,按照关键字找到相应节点,输出此节点的前驱节点关键字及后继节点关键字。输入
第一行两个正整数n(代表节点个数),m(代表要找的关键字的个数)。接下来n行每行有一个整数为关键字key(数据保证关键字在数列中没有重复)。接下来有m个关键字,每个占一行。输出
对给定的每个关键字,输出此关键字前驱节点关键字和后继节点关键字。如果给定的关键字没有前驱或者后继,则不输出。给定关键字为每个输出占一行。示例输入
10 3 1 2 3 4 5 6 7 8 9 0 3 5 0
示例输出
2 4 4 6 9
(一)单链表法#include <stdio.h>#include <stdlib.h>struct node{int data;struct node *next;} ;//定义链表的节点struct node *creat(int n){int i;struct node *head,*p,*tail;head=(struct node *)malloc(sizeof(struct node));head->next=NULL;tail=head;for(i=0; i<n; i++){p=(struct node *)malloc(sizeof(struct node));scanf("%d",&p->data);p->next=NULL;tail->next=p;tail=p;}return head;};//顺序建立链表struct node *found(struct node *head,int key)//查找函数{struct node *p,*q;p=head->next;q=head;while(p->next!=NULL){if(p->data==key){if(q==head)printf("%d\n",p->next->data);elseprintf("%d %d\n",q->data,p->next->data);break;}q=p;p=p->next;}if(p->next==NULL)printf("%d\n",q->data);return NULL;};int main(){int key,n,m,i;struct node *head;scanf("%d %d",&n,&m);head=creat(n);for(i=0; i<m; i++){scanf("%d",&key);found(head,key);}return 0;}
(二)双向链表法#include <stdio.h>#include <string.h>#include <stdlib.h>struct node{int data;struct node *last;//保存前一个节点的地址struct node *next;};struct node *creat(int n)//建立双向链表{int i;struct node *head,*p,*tail;head=(struct node *)malloc(sizeof(struct node));head->next=NULL;head->last=NULL;tail=head;for(i=0;i<n;i++){p=(struct node *)malloc(sizeof(struct node));scanf("%d",&p->data);p->next=NULL;p->last=tail;tail->next=p;tail=p;}return head;};void ser(struct node *head){int key;struct node *p;scanf("%d",&key);p=head->next;while(p!=NULL){if(p->data==key){if(p->next!=NULL&&p->last==head){printf("%d\n",p->next->data);break;}else if(p->next!=NULL&&p->last!=head){printf("%d %d\n",p->last->data,p->next->data);break;}else{printf("%d\n",p->last->data);break;}}p=p->next;}}int main(){int n,m,i;struct node *head;scanf("%d %d",&n,&m);head=creat(n);for(i=0;i<m;i++)ser(head);return 0;}
相关文章推荐
- 山东理工OJ【2054】双向链表(两种方法)
- 山东理工OJ【2122】数据结构实验之链表七:单链表中重复元素的删除(两种思想)
- 华为OJ机试题目:两个大整数相乘(纯C语言实现两个大整数相乘,两种方法实现大数相乘)
- CSDN博客和OJ,两种积累编程代码量的方法对比
- ZZUOJ 1199 大小关系(拓扑排序,两种方法_判断入度和dfs回路判断)
- 对比XP和FDD两种软件开发方法
- 关于服务器端数据访问(2)两种方法访问基于 SQL 的数据 :
- DotNet开发中关于SQLServer连接的两种方法之比较
- .net调用别人的http页面,返回结果,url中有中文的处理,get和post两种方法
- 网页中文本复制的两种方法
- 两种方法删除ArrayList里重复元素
- 建立数据库结构的两种方法
- JavaBean实现多个文件上传的两种方法
- 导出excel的两种方法
- RFC948_IP 数据包通过IEEE 802.3 网络传输的两种方法
- 取得拨号上网时动态分配IP的两种方法
- 工资系统设计两种方法
- 导出excel的两种方法
- 在delphi中使用xml文档有两种方法
- ASP创建SQL Server数据库的两种方法