链表中下一个更大节点
#include<stdio.h>
#include<stdlib.h>
typedef int elemtype;
typedef struct _node{
elemtype data;
int idx;
struct _node *next;
}Node;
typedef struct {
Node *head;
Node *tail;
int len;
}List;
typedef struct{
elemtype a[20];
int idx[20];
int top;
}Stack;
List* InitList()
{
List *pl=(List *)malloc(sizeof(List));
pl->head=pl->tail=(Node *)malloc(sizeof(Node));
pl->head->next=NULL;
pl->len=0;
return pl;
}
Stack* InitStack()
{
Stack *s=(Stack *)malloc(sizeof(Stack));
s->top=0;
return s;
}
void AddList(List *plist)
{
printf("please input the data of node untill -1\n");
while(1)
{
Node *p=(Node *)malloc(sizeof(Node));
p->next=NULL;
scanf("%d",&p->data);
p->idx=plist->len;
if(p->data==-1)
{
free(p);
break;
}
plist->tail->next=p;
plist->tail=p;
plist->len++;
}
}
void print(List *plist)
{
Node *p;
for ( p=plist->head->next;p;p=p->next )
{
printf("%d (%d) --",p->data,p->idx);
}
}
void clean_up(List *plist)
{
Node *p,*q;
for ( p=plist->head,q=NULL;p;p=q )
{
q=p->next;
free(p);
}
}
int Empty(Stack *s)
{
if(s->top==0)
return 1;
else
return 0;
}
int push(Stack *s,elemtype x,int idx)
{
if(s->top==20)
return 0;
else
{
s->a[s->top]=x;
s->idx[s->top]=idx;
s->top++;
return 1;
}
}
int pop(Stack *s,elemtype* x,int *idx)
{
if(Empty(s))
return 0;
else
{
s->top--;
*x=s->a[s->top];
*idx=s->idx[s->top];
return 1;
}
}
int GetTop(Stack *s)
{
if(Empty(s))
return 0;
else
return s->a[s->top-1];
}
int main()
{
List *plist=InitList();
AddList(plist);
int idx;
int x;
int result[plist->len];
Stack *s=InitStack();
Node *p=plist->head->next;
if(!p)
{
return 0;
}
while(p)
{
while( ( !Empty(s) ) && p->data>GetTop(s) )
{
pop(s,&x,&idx);
result[idx]=p->data;
}
push(s,p->data,p->idx);
p=p->next;
}
while(!Empty(s))
{
pop(s,&x,&idx);
result[idx]=-1;
}
for ( idx=0;idx<plist->len;idx++)
{
printf("%d ",result[idx]);
}
}