LinkedStack.h
#ifndef _LINKEDSTACK_H
#define _LINKEDSTACK_H
typedef int data_t;
typedef struct node
{
data_t data;
struct node *next;
} listnode, *pLinkStack;
pLinkStack StackCreate();
int StackPush(pLinkStack s, data_t value);
data_t StackPop(pLinkStack s);
int StackEmpty(pLinkStack s);
data_t StackTop(pLinkStack s);
pLinkStack StackFree(pLinkStack s);
int StackShow(pLinkStack s);
#endif
LinkedStack.c
#include <stdio.h>
#include <stdlib.h>
#include "LinkedStack.h"
pLinkStack StackCreate()
{
pLinkStack s = (pLinkStack)malloc(sizeof(listnode));
if (s == NULL)
{
printf("StackCreate:Space allocation failed\n");
return NULL;
}
s->data = 0;
s->next = NULL;
return s;
}
int StackPush(pLinkStack s, data_t value)
{
if (s == NULL)
{
printf("StackPush:invalid parameter\n");
return -1;
}
pLinkStack p = (pLinkStack)malloc(sizeof(listnode));
if (p == NULL)
{
printf("StackPush:Space allocation failed\n");
return -1;
}
p->data = value;
p->next = s->next;
s->next = p;
return 0;
}
data_t StackPop(pLinkStack s)
{
data_t temp_val;
pLinkStack p;
if (s == NULL)
{
printf("StackPop:invalid parameter\n");
return -1;
}
temp_val = s->next->data;
p = s->next;
s->next = p->next;
p->next = NULL;
free(p);
return temp_val;
}
int StackEmpty(pLinkStack s)
{
if (s == NULL)
{
printf("StackEmpty:invalid parameter\n");
return -1;
}
if (s->next != NULL)
{
return 0;
}
return 1;
}
data_t StackTop(pLinkStack s)
{
if (s == NULL)
{
printf("StackTop:invalid parameter\n");
return -1;
}
return s->next->data;
}
pLinkStack StackFree(pLinkStack s)
{
pLinkStack p;
if (s == NULL)
{
printf("StackTop:invalid parameter\n");
return NULL;
}
while (s != NULL)
{
p = s;
s = s->next;
printf("free:%d\n", p->data);
free(p);
}
return NULL;
}
int StackShow(pLinkStack s)
{
if (s == NULL)
{
printf("StackShow:invalid parameter\n");
return -1;
}
pLinkStack p = s->next;
while (p != NULL)
{
printf("%d ", p->data);
p = p->next;
}
puts("");
return 0;
}
main.c
#include <stdio.h>
#include "LinkedStack.h"
void test_StackPush();
void test_StackPop();
int main(int argc, char const *argv[])
{
// test_StackPush();
test_StackPop();
return 0;
}
void test_StackPush()
{
pLinkStack s = StackCreate();
StackPush(s, 1);
StackPush(s, 2);
StackPush(s, 3);
StackPush(s, 4);
StackPush(s, 5);
StackPush(s, 6);
StackShow(s);
}
void test_StackPop()
{
pLinkStack s = StackCreate();
StackPush(s, 1);
StackPush(s, 2);
StackPush(s, 3);
StackPush(s, 4);
StackPush(s, 5);
StackPush(s, 6);
StackShow(s);
StackPop(s);
StackShow(s);
}
标签:return,04,StackPush,next,pLinkStack,链式,NULL,data
From: https://www.cnblogs.com/goldenFantome/p/17615574.html