#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<stdlib.h>
#include<stdbool.h>
typedef struct Stacknode{
int data;
struct Stacknode *next;
}Stacknode,*Liststack;
//初始化一个空栈
bool initstack(Liststack &l)
{
l=(Stacknode*)malloc(sizeof(Stacknode));
if(l==NULL) //内存分配失败
return false;
l->next=NULL;
return true;
}
//链栈判空操作
bool Emptystack(Liststack l)
{
if(l->next==NULL)
return true;
else
return false;
}
//进栈(其实就是对头结点的后插操作(把链头看做栈顶,只能对头结点进行操作)
bool push(Liststack l, int x)
{
if(l==NULL) //栈空(没有头结点
return false;
Stacknode *s = (Stacknode*)malloc(sizeof(Stacknode));
if(s==NULL)
return false;
s->data=x;
s->next = l->next;
l->next =s;
return true;
}
//出栈(相当于对头结点的“后删”操作
bool pop(Liststack l,int &e)
{
if(l==NULL||l->next==NULL)//没有头结点或者头结点后没有结点
return false;
Stacknode *q;
q= l->next;
e=q->data;
l->next=q->next;
free(q);
return true;
}
//打印栈
bool print(Liststack l)
{
if(l==NULL || l->next==NULL)//没有头结点或者头结点后没有结点
return false;
Stacknode *p =l->next;
while (p != NULL) {
printf("%d\n",p->data);
p=p->next;
}
return true;
}
//求栈的长度
int length(Liststack l)
{
int len=0;
Stacknode *p=l->next;
while (p != NULL) {
p=p->next;
len++;
}
return len;
}
//获取栈顶元素
bool gettop(Liststack l)
{
if(l==NULL || l->next==NULL)//没有头结点或者头结点后没有结点
return false;
printf("%d\n",l->next->data); //打印栈顶元素
return true;
}
int main()
{
Liststack l;
initstack(l);
push(l,1);
push(l,2);
push(l,3);
print(l);
printf("长度%d\n",length(l));
int e;
pop(l,e);
print(l);
printf("%d\n",e);
gettop(l);
return 0;
}
C语言——带头结点的链栈
于 2022-09-18 11:51:15 首次发布