用一个单链表L实现一个栈 要求PUSH和POP操作的时间仍为O(1) 算法导论10.2-2答案

#include <stdio.h>
#include <stdlib.h>
#define NULL 0
typedef struct Stack *S1;
typedef struct Node
{
	int Element;
	Node *next;
}Snode,*node;

struct Stack
{
	Snode *top;
};

S1 InitStack()
{
	S1 s;
	s=(S1)malloc(sizeof(struct Stack));
	s->top=(node)malloc(sizeof(struct Node));
	s->top->next=NULL;
	s->top->Element=NULL;
	return s;
}

void Push(int x,S1 s)
{
	node n;
	n=(node)malloc(sizeof(struct Node));
	if(!n)
		exit(-1);
	n->Element=x;
	n->next=s->top->next;
	s->top->next=n;
}

int Pop(S1 s)
{
	if(s->top->next!=NULL)
	{
		int i;
    	node p=s->top->next;
		i=p->Element;
    	s->top->next=p->next;
    	free(p);
		return i;
	}
	else
		exit(-1);
}

void main()
{
	S1 st;
	int i;
	st=InitStack();
	Push(1,st);
	Push(2,st);
	Push(3,st);
	i=Pop(st);
	printf("%d\n",i);
	Push(5,st);
	Push(9,st);
	i=Pop(st);
	printf("%d\n",i);	
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值