数据结构——链栈

这几天的学习下来,我现在对于代码的理解能力有了显著的提升,以至于现在在自己代码内的注解也越来越少了。今天的链栈也是相对比较简单的,除了结构与链表相同,表示方式与顺序栈几乎并无太大的差别,所以直接将代码写出来了~

#include<stdio.h>

/*创立一个链栈结点*/
typedef struct stacknode{
	int data;
	struct stacknode *next;
}stacknode;

/*创建一条链栈*/ 
typedef struct{
	stacknode *top;
}linkstack;

void initstack(linkstack *s){
	s->top = NULL;
	printf("初始化成功!");
}

/*将链栈置空*/
int setempty(linkstack *s){
	stacknode *p = s->top;
	while(p){
		s->top = p->next;
		free(p);
		p = s->top;
	}
	printf("链栈已置空!");
	return 1; 
}

/*入栈*/ 
int push(linkstack *s, int e){
	stacknode *p;
	p = (stacknode *)malloc(sizeof(stacknode));
	p->data = e;
	p->next = s->top;
	s->top = p;
	return 1;
}

/*出栈*/
int pop(linkstack *s, int *e){
	stacknode *p = s->top;
	if(s->top == NULL){
		printf("栈空!");
		exit(0); 
	}
	s->top = p->next;
	*e = p->data;
	free(p);
	return 1;
}

/*栈顶元素*/ 
int gettop(linkstack *s, int *e){
	if(s->top == NULL){
		printf("栈空!");
		exit(0);
	}
	*e = s->top->data;
	return 1;
}

/*显示栈内元素*/ 
int display(linkstack *s){
	stacknode *p;
	p = s->top;
	while(p){
		printf("%d ", p->data);
		p = p->next;
	}
	printf("\n");
	return 1;
}

int main(){
	linkstack s;
	initstack(&s);
	int n, e, a;
	printf("请输入链栈的长度:");
	scanf("%d", &n);
	puts("请输入想要录入的数据:");
	while(n--){
		int x;
		scanf("%d", &x);
		push(&s, x);
	} 
	display(&s);
	gettop(&s, &e);
	printf("栈顶元素为:%d\n", e);
	printf("入栈新元素:");
	scanf("%d", &a);
	push(&s, a);
	display(&s);
	printf("出栈元素为:%d\n", a);
	pop(&s, &e);
	display(&s);
	setempty(&s);
	return 0;
}

上一篇:Java面试基础(中)


下一篇:Java基础面试突击