数据结构实验之栈五:下一较大值(一)
Time Limit: 1000MS Memory limit: 65536K
题目描述
对于包含n(1<=n<=1000)个整数的序列,对于序列中的每一元素,在序列中查找其位置之后第一个大于它的值,如果找到,输出所找到的值,否则,输出-1。
输入
输入有多组,第一行输入
t
(
1<=t<=10
),表示输入的组数;
以后是 t组输入:每组先输入n,表示本组序列的元素个数,之后依次输入本组的n个元素。
输出
输出有多组,每组之间输出一个空行(最后一组之后没有);
每组输出按照本序列元素的顺序,依次逐行输出当前元素及其查找结果,两者之间以-->间隔。
示例输入
2 4 12 20 15 18 5 20 15 25 30 6
示例输出
12-->20 20-->-1 15-->18 18-->-1 20-->25 15-->25 25-->30 30-->-1 6-->-1
#include<stdio.h> #include<stdlib.h> #include<string.h> struct node { int data; struct node *next; }; struct node *create(int n) { int i; struct node *head,*p,*q,*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; }; int search_nextbig(struct node*head) { struct node *p,*q; for(p=head->next;p!=NULL;p=p->next) { q=p->next; while(q!=NULL) { if(q->data>p->data) { printf("%d-->%d\n",p->data,q->data); break; } else q=q->next; } if(q==NULL) printf("%d-->-1\n",p->data); } } int main() { int n,i,m; scanf("%d",&n); struct node*head; while(n--) { scanf("%d",&m); head=create(m); search_nextbig(head); if(n>0)printf("\n"); } return 0; }