数据结构与算法系列-栈-链栈

栈的链式存储结构简称为链栈,他是一种特殊的单链表,也是一种动态存储结构,通常不会发生栈的溢出,不用预先分配存储空间。

单链表的头部节点称为栈顶,尾部节点称为栈底.


链栈节点的定义

数据域                      指针域

datanext

链栈的定义与基本操作

进栈

当向链栈插入一个新元素时,首先要向系统申请一个结点的存储空间,将新元素的值写入新结点的数据中,然后修改栈顶指针

#include<malloc.h>
#include<stdio.h>
typedef struct node{
	int data;
	struct node *next;
}NODE;//定义栈链结点

NODE *create_linkstack(){
	NODE *top,*p;
	int a,n;
	top =NULL;
	printf("\n Input number of push linkstack: ");
	scanf("%d",&n);
	if(n>0){
		printf("Input %d elements of push linkstack: ",n);
		while(n>0){
			scanf("%d",&a);
			p = (NODE *)malloc(sizeof(NODE));
			p->data = a;
			p->next = top;
			top = p;
			n--;
		}
	}
	return (top);/*返回栈顶指针*/
}

NODE *pushstack(NODE *top,int x){/*进栈*/
	NODE *p;
	p = (NODE *)malloc(sizeof(NODE));
	p->data = x;/*将要插入的数据x存储到结点p的数据域中*/
	p->next = top;/*将p插入到链表的头部 即栈顶*/
	top = p;
	return (top);
}

void print(NODE *top){/*输出栈元素*/
	NODE *p;
	p=top;
	if(p!=NULL){
		printf("output the element of stack: ");
		while(p!=NULL){
			printf("%3d",p->data);
			p = p->next;
		}
	}else
		printf("\nThe stack is empty");
}
main(){
	int y;
	NODE *a;
	a = create_linkstack();
	print(a);
	printf("\n push an element to linksack");
	scanf("%d",&y);
	a = pushstack(a,y);
	print(a);
}




出栈

当出栈时,先取出栈顶元素,再修改栈顶指针,释放原栈顶节点

#include<malloc.h>
#include<stdio.h>
typedef struct node{
	int data;
	struct node *next;
}NODE;

NODE *create_linkstack(){
	NODE *top,*p;
	int a,n;
	top = NULL;
	printf("\nInput number of push linkstack: ");
	scanf("%d",&n);
	if(n>0){
		printf("Input %d elements of push linkstack:",n);
		while(n>0){
			scanf("%d",&a);
			p = (NODE *)malloc(sizeof(NODE));
			p->data = a;
			p->next = top;
			top = p;
			n--;
		}
	}
	return (top);
}

NODE *popstack(NODE *top,int *p){
	NODE *q;
	if(top!=NULL){
		q = top;
		*p = top->data;/*将栈顶元素放入p中*/
		top = top->next;/*修改top指针*/
		free(q);/*释放原栈顶*/
	}
	return (top);
}

void print(NODE *top){/*输出栈元素*/
	NODE *p;
	p=top;
	if(p!=NULL){
		printf("output the element of stack: ");
		while(p!=NULL){
			printf("%3d",p->data);
			p = p->next;
		}
	}else
		printf("\nThe stack is empty");
}

main(){
	int y= 0;
	NODE *a;
	a= create_linkstack();
	print(a);
	a= popstack(a,&y);
	printf("\nOutput the element of poplinkstack: %d\n",y);
	print(a);
}




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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值