链表栈基本操作
编译环境:VS !!
对应操作已写注解!!
#include <stdio.h>
#include <stdlib.h>
typedef char datatype;
//创建栈中的元素结构体(单链表)
typedef struct node
{
datatype data; //数据域
struct node *next; //后继指针
} stacknode;
//创建栈的结构体
typedef struct
{
stacknode *top; //栈的头指针
} linkstack;
//创建新结点
stacknode *buystacknode(datatype d)
{
stacknode *newnode = (stacknode *)malloc(sizeof(stacknode));
if (newnode == NULL)
{
printf("结点内存分配失败\n");
exit(1);
}
newnode->data = d;
newnode->next = NULL;
return newnode;
}
//初始化栈
void initstack(linkstack *s)
{
s->top = NULL;
}
//入栈
void push(linkstack *s, datatype d)
{
stacknode *newnode = buystacknode(d);
if (s->top == NULL)
{
/* code */
s->top = newnode;
}
else
{
newnode->next = s->top;
s->top = newnode;
}
printf("入栈成功!\n");
}
//出栈
void pop(linkstack *s)
{
stacknode *cur = s->top;
if (s->top == NULL)
{
/* code */
printf("链表栈为空!");
exit(1);
}
else
{
s->top = cur->next;
free(cur);
printf("出栈成功!\n");
}
}
//打印栈元素
void printstack(linkstack *s)
{
stacknode *cur = s->top;
while (cur != NULL)
{
/* code */
printf("%c", cur->data);
cur = cur->next;
}
printf("\n");
}
//打印栈长度
void stacklength(linkstack *s)
{
stacknode *cur = s->top;
int j = 0;
while (cur != NULL)
{
j++;
cur = cur->next;
}
printf("该栈长度为:%d\n",j);
}
//测试
int main(int argc, char const *argv[])
{
linkstack s;
initstack(&s);
push(&s, 'a');
push(&s, 'b');
push(&s, 'c');
push(&s, 'd');
printstack(&s);
stacklength(&s);
pop(&s);
pop(&s);
pop(&s);
printstack(&s);
stacklength(&s);
return 0;
}
运行结果
该文章作为学习记录,水平有限。如有差错,请多多指点!!🐵