今天是顺序栈的升级,用链式存储结构来实现栈,新手上路,多多关照
链栈
链栈的存储结构与单链表的存储结构相同。由于栈是在栈顶进行删除和添加元素的,因此,将链表的首部作为栈顶是最方便的。而且没有必要像单链表那样为了操作简单而附加一个头结点。
基本操作
定义
typedef int StackElementType;
typedef struct Node{
StackElementType data;
struct Node *next;
}Node,*LinkList;
和链表一模一样
入栈
void Push(LinkList S,char x)//入栈
{
Node *temp = (Node*)malloc(sizeof(Node));
temp->next = S->next;
temp->data=x;
S->next=temp;
return;
}
注意传地址 就是头插法
出栈
void Pop(Node *S,int *x)//出栈
{
Node *temp=S->next;
if(temp==NULL) {printf("WRONG\n");return ;}
S->next=temp->next;
*x=temp->data;
free(temp);
return ;
}
先进后出
得到栈顶元素
void GetTop(Node *S,int *x)
{
if(S->next==NULL) {printf("EMPTY\n");return ;}
*x=S->next->data;
return ;
}
主函数
#include<stdio.h>
#include<stdlib.h>
typedef int StackElementType;
typedef struct Node{
StackElementType data;
struct Node *next;
}Node,*LinkList;
void Push(LinkList S,char x)//入栈
{
Node *temp = (Node*)malloc(sizeof(Node));
temp->next = S->next;
temp->data=x;
S->next=temp;
return;
}
void Pop(Node *S,int *x)//出栈
{
Node *temp=S->next;
if(temp==NULL) {printf("WRONG\n");return ;}
S->next=temp->next;
*x=temp->data;
free(temp);
return ;
}
void GetTop(Node *S,int *x)
{
if(S->next==NULL) {printf("EMPTY\n");return ;}
*x=S->next->data;
return ;
}
int main()
{
Node *S=(Node*)malloc(sizeof(Node));
S->next=NULL;
char x;
Push(S,'A');//注意不用加&,因为定义Node*为指针结构了
Pop(&S,&x);
printf("%c\n",x);
Pop(&S,&x);
GetTop(&S,&x);
return ;
}