数据结构与算法系列-栈-链栈
2013-11-10 20:55
260 查看
栈的链式存储结构简称为链栈,他是一种特殊的单链表,也是一种动态存储结构,通常不会发生栈的溢出,不用预先分配存储空间。
单链表的头部节点称为栈顶,尾部节点称为栈底.
链栈节点的定义
数据域 指针域
链栈的定义与基本操作
进栈
当向链栈插入一个新元素时,首先要向系统申请一个结点的存储空间,将新元素的值写入新结点的数据中,然后修改栈顶指针
出栈
当出栈时,先取出栈顶元素,再修改栈顶指针,释放原栈顶节点
单链表的头部节点称为栈顶,尾部节点称为栈底.
链栈节点的定义
数据域 指针域
data | next |
进栈
当向链栈插入一个新元素时,首先要向系统申请一个结点的存储空间,将新元素的值写入新结点的数据中,然后修改栈顶指针
#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); }
相关文章推荐
- 数据结构与算法系列-线性表-线性表的应用
- 数据结构与算法系列-串-串的基本概念与存储结构
- 数据结构与算法(C#实现)系列-----前言
- 数据结构与算法学习系列第一天
- 数据结构与算法(C#实现)系列---演示篇(一)
- 数据结构与算法系列----AC自己主动机
- 数据结构与算法(C#实现)系列
- 数据结构与算法(C#实现)系列---演示篇(三)_C#教程
- 数据结构与算法(C#实现)系列---N叉树(二) _C#教程
- 数据结构与算法系列----基数排序
- 数据结构系列-链栈的基本操作
- 数据结构与算法系列-线性表-数组(线性表的推广)
- 数据结构与算法系列-串-串的基本操作
- 数据结构与算法(C#实现)系列---二叉堆(数组实现)
- 数据结构与算法系列之一:八大排序综述
- 数据结构与算法(C#实现)系列---树
- 数据结构与算法(C#实现)系列---树(一)
- 数据结构与算法系列——从菜鸟到入门
- 数据结构与算法系列----判断线段相交
- 数据结构与算法(C#实现)系列---树(一)_C#教程