Time Limit: 1000MS Memory Limit: 65536KB
Problem Description
學會了單向鏈表,我們又多了一種解決問題的能力,單鏈表利用一個指針就能在內存中找到下一個位置,這是一個不會輕易斷裂的鏈。但單鏈表有一個弱點——不能回指。比如在鏈表中有兩個節點A,B,他們的關係是B是A的後繼,A指向了B,便能輕易經A找到B,但從B卻不能找到A。一個簡單的想法便能輕易解決這個問題——建立雙向鏈表。在雙向鏈表中,A有一個指針指向了節點B,同時,B又有一個指向A的指針。這樣不僅能從鏈表頭節點的位置遍歷整個鏈表所有節點,也能從鏈表尾節點開始遍歷所有節點。對於給定的一列數據,按照給定的順序建立雙向鏈表,按照關鍵字找到相應節點,輸出此節點的前驅節點關鍵字及後繼節點關鍵字。
Input
第一行兩個正整數n(代表節點個數),m(代表要找的關鍵字的個數)。第二行是n個數(n個數沒有重複),利用這n個數建立雙向鏈表。接下來有m個關鍵字,每個佔一行。
Output
對給定的每個關鍵字,輸出此關鍵字前驅節點關鍵字和後繼節點關鍵字。如果給定的關鍵字沒有前驅或者後繼,則不輸出。
注意:每個給定關鍵字的輸出佔一行。
一行輸出的數據之間有一個空格,行首、行末無空格。
Example Input
10 3
1 2 3 4 5 6 7 8 9 0
3
5
0
Example Output
Hint
Author
參考代碼
#include<stdio.h>
#include<malloc.h>
#include<stdlib.h>
struct node
{
int data;
struct node *next;
struct node *re;
};
void sec(struct node *head,int n)
{
struct node *p;
p = head->next;
while(p)
{
if(p->data == n)
{
if(p->next && p->re->re)
printf("%d %d\n",p->re->data,p->next->data);
else if(p->next == NULL)
{
printf("%d\n",p->re->data);
}
else
{
printf("%d\n",p->next->data);
}
break;
}
p = p->next;
}
}
int main()
{
int n,m;
int i,t;
struct node *head,*p,*tail;
head = (struct node *)malloc(sizeof(struct node));
head->next = NULL;
head->re = NULL;
tail = head;
scanf("%d%d",&n,&m);
for(i = 0; i < n; i++)
{
p = (struct node *)malloc(sizeof(struct node));
scanf("%d",&p->data);
p->next = tail->next;
p->re = tail;
tail->next = p;
tail = p;
}
while(m--)
{
scanf("%d",&t);
sec(head,t);
}
return 0;
}