#pragma once
#include <stdio.h>
#include <stdlib.h>
typedef int data_t;
typedef struct node
{
data_t data;
struct node* next;
}linknode, *linkstack;
//创建新节点
linkstack linkstack_creat();
//链式栈压栈
int linkstack_push(linkstack p, data_t val);
//出栈
data_t linkstack_pop(linkstack p);
//打印栈
void linkstack_show(linkstack p);
//释放动态开辟空间
int linkstack_free(linkstack* p);
头文件LinkStack.h
#include "LinkStack.h"
linkstack linkstack_creat()
{
linkstack p;
p = (linkstack)malloc(sizeof(linknode));
if (p == NULL)
{
printf("Malloc Error.\n");
return NULL;
}
p->data = 0;
p->next = NULL;
return p;
}
int linkstack_push(linkstack p, data_t val)
{
if (p == NULL)
{
printf("Pointer is NULL.\n");
return -1;
}
linkstack newnode = linkstack_creat();
while (p->next != NULL)
{
p = p->next;
}
p->next = newnode;
newnode->data = val;
return 0;
}
data_t linkstack_pop(linkstack p)
{
if (p == NULL)
{
printf("Pointer is NULL.\n");
return -1;
}
if (p->next == NULL)
{
printf("Stack is empty.\n");
return -1;
}
data_t val;
linkstack temp;
temp = p;
while (temp->next != NULL)
{
temp = temp->next;
}
val = temp->data;
return val;
}
void linkstack_show(linkstack p)
{
if (p == NULL)
{
printf("Pointer is NULL.\n");
return;
}
if (p->next == NULL)
{
printf("Stack is empty.\n");
return;
}
int i = 0;
linkstack temp = p;
//检测链表长度,以便从栈顶开始打印
while (temp->next != NULL)
{
temp = temp->next;
i++;
}
while (i > 0)
{
temp = p;
for (size_t j = i; j > 0; j--)
{
temp = temp->next;
}
printf("%d\t%p\n", temp->data, &(temp->data));
i--;
}
}
int linkstack_free(linkstack* p)
{
if (p == NULL)
{
printf("Pointer is NULL.\n");
return -1;
}
linkstack temp;
while (*p != NULL)
{
temp = *p;
*p = (*p)->next;
free(temp);
}
return 0;
}
函数实现LinkStack.c
#include "LinkStack.h"
int main()
{
linkstack p;
p = linkstack_creat();
//test
for (int i = 1; i < 6; i++)
{
linkstack_push(p, i);
}
linkstack_show(p);
linkstack_pop(p);
linkstack_show(p);
linkstack_free(&p);
//
return 0;
}
测试函数test.c
释放动态空间时也可以不使用二级指针,将linkstack_free定义为返回值为结构体指针linkstack类型的函数,在调用函数时使用头结点指针接收返回值NULL即可。
//LinkStack.h
linkstack linkstack_free(linkstack p);
//test.c
p = linkstack_free(p);
//LinkStack.c
linkstack linkstack_free(linkstack p)
{
if (p == NULL)
{
printf("Pointer is NULL.\n");
return -1;
}
linkstack temp;
while (p != NULL)
{
temp = p;
p = p->next;
free(temp);
}
return 0;
}