堆栈 链表的实现方式

main函数给出实验数据。

#include<stdio.h>
#include<stdlib.h>
typedef struct node
{
	int a;
	struct node *next;
}stack;

stack *create_stack()
{
	stack *s = (stack*)malloc(sizeof(struct node));
	if (s == NULL)
		return NULL;
	else
	{
		s->next = 0; return s;
	}
}

int empty_stack(stack *s)
{
	if (s->next == 0) return 0;
	else return 1;
}

int push(stack *s, int m)
{
	stack *temp = (stack *)malloc(sizeof(struct node));
	temp->a = m;
	temp->next = s->next;
	s->next = temp;
	return 1;
}

int pop(stack *s)
{
	stack *temp;
	int t;
	if (!empty_stack(s))  return 0;
	else{
		temp = s->next;
		t = temp->a;
		s->next = temp->next;
		free(temp);
		return t;
	}
}

void print_stack(stack *s)
{
	stack *t=s->next;
	while (t)
	{
		printf("%d ", t->a);
		t = t->next;
	}
}

int main()
{
	int b[10] = { 55, 66, 9, 7, 4, 2, 0 };
	stack *s = create_stack();
	push(s, b[0]);
	push(s, b[1]);
	push(s, b[2]);
	pop(s);
	print_stack(s);
}

猜你喜欢

转载自blog.csdn.net/youtiankeng/article/details/87719292