链表中下一个更大节点

链表中下一个更大节点

#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);
//	print(plist);
	int idx;
	int x;
	int result[plist->len]; 
	Stack *s=InitStack();
	
	
	Node *p=plist->head->next;
	//判空
	if(!p)
	{
		return 0;
	}
	
	
	
	while(p)
	{
		//判空操作在前,如果是空的,就不能用GetTop()函数 
		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]);
	}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值