您的位置:首页 > 理论基础 > 数据结构算法

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

2013-11-10 20:55 260 查看
栈的链式存储结构简称为链栈,他是一种特殊的单链表,也是一种动态存储结构,通常不会发生栈的溢出,不用预先分配存储空间。

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



链栈节点的定义

数据域 指针域

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);
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: