Description
学会了单向链表,我们又多了一种解决问题的能力,单链表利用一个指针就能在内存中找到下一个位置,这是一个不会轻易断裂的链。但单链表有一个弱点——不能回指。比如在链表中有两个节点A,B,他们的关系是B是A的后继,A指向了B,便能轻易经A找到B,但从B却不能找到A。一个简单的想法便能轻易解决这个问题——建立双向链表。在双向链表中,A有一个指针指向了节点B,同时,B又有一个指向A的指针。这样不仅能从链表头节点的位置遍历整个链表所有节点,也能从链表尾节点开始遍历所有节点。对于给定的一列数据,按照给定的顺序建立双向链表,按照关键字找到相应节点,输出此节点的前驱节点关键字及后继节点关键字。
Input
第一行两个正整数n(代表节点个数),m(代表要找的关键字的个数)。接下来n行每行有一个整数为关键字key(数据保证关键字在数列中没有重复)。接下来有m个关键字,每个占一行。
Output
对给定的每个关键字,输出此关键字前驱节点关键字和后继节点关键字。如果给定的关键字没有前驱或者后继,则不输出。给定关键字为每个输出占一行。
Sample Input
10 31 2 3 4 5 6 7 8 9 0350
Sample Output
2 44 69
#include <cstdio> #include <iostream> #include <cstdlib> #include <cstring> #include <algorithm> #include <vector> using namespace std; typedef struct node //双向链表 { int date; node *front,*next; }*S,list; void create_list1(S head,int n) // { S p,t; p=head; while(n--) { t=new list; cin>>t->date; t->front=p; t->next=NULL; p->next=t; p=t; } } void output_list(S head)//输出链表 { S p=head->next; while(p!=NULL) { if(p->next!=NULL) cout<<p->date<<" "; else cout<<p->date<<endl; p=p->next; } } S find_list(S head,int x) { S p=head->next; while(p!=NULL) { if(p->date==x) return p; p=p->next; } return p; } int main() { int n,x,m; S pos,head=new list; head->next=NULL; head->front=NULL; head->date=-1; cin>>n>>m; create_list1(head,n); while(m--) { cin>>x; if(find_list(head,x)!=NULL) { pos=find_list(head,x); if(pos->front->front==NULL&&pos->next!=NULL) cout<<pos->next->date<<endl; else if(pos->front->front!=NULL&&pos->next==NULL) cout<<pos->front->date<<endl; else if(pos->front->front!=NULL&&pos->next!=NULL) cout<<pos->front->date<<" "<<pos->next->date<<endl; } } return 0; }