數據結構實驗之鏈表九:雙向鏈表
Time Limit: 1000 ms Memory Limit: 65536 KiB
Submit Statistic
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
#include<stdio.h> #include<iostream> #include <bits/stdc++.h> using namespace std; struct node { int data; struct node *pre,*next; }; struct node *cr(int n) //順序建雙向鏈表 { struct node *head,*t,*p; head=new node; head->next=NULL; //後繼和前驅都初始爲空 head->pre=NULL; t=head; for(int i=0; i<n; i++) { p=new node ; scanf("%d",&p->data); p->pre=t; //與單鏈表建表的不同就在於此,將新節點的前驅指針指向上一個結點。 p->next=NULL; t->next=p; // 尾指針永遠指向最新結點即最後一個結點。 t=p; } return head; } void find(node *head,int k) { node *p=head->next; while(p!=NULL) { if(p->data==k) { if(p->pre!=head&&p->next!=NULL) printf("%d %d\n",p->pre->data,p->next->data); else if(p->pre==head) printf("%d\n",p->next->data); else if(p->next==NULL) printf("%d\n",p->pre->data); } p=p->next; } } int main() { int n,m; scanf("%d %d",&n,&m); node *head; //等於struct node*head; head=cr(n); while(m--) { int k; scanf("%d",&k); find(head,k); } return 0; }