栈(C语言版,尾插法,使用头节点)
作者:互联网
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
typedef struct Node {
int data;
struct Node *pNext;
}NODE, *PNODE;
typedef struct Stack {
PNODE pTop;
PNODE pBottom;
}STACK, *PSTACK;
void init(PSTACK pS);
bool push(PSTACK, int);
bool is_empty(PSTACK);
void traverse(PSTACK);
bool pop(PSTACK, int *);
bool pop(PSTACK pS, int *pVal)
{
if (is_empty(pS))
return false;
*pVal = pS->pTop->data;
PNODE q = pS->pTop;
pS->pTop = q->pNext;
free(q);
q = NULL;
return true;
}
void traverse(PSTACK pS)
{
PNODE p = pS->pTop;
if (is_empty(pS)) {
printf("stack is empty.\n");
return;
}
while (p->pNext != NULL) {
printf("%d ", p->data);
p = p->pNext;
}
printf("\n");
}
bool is_empty(PSTACK pS)
{
if (pS->pTop == pS->pBottom)
return true;
return false;
}
bool push(PSTACK pS, int val)
{
PNODE pNew = (PNODE)malloc(sizeof(NODE));
if (NULL == pNew) {
printf("内存分配失败");
return false;
}
pNew->data = val;
pNew->pNext = pS->pTop;
pS->pTop = pNew;
return true;
}
void init(PSTACK pS)
{
PNODE pNew = (PNODE)malloc(sizeof(NODE));
if (NULL == pNew) {
printf("内存分配失败");
exit(-1);
}
pNew->pNext = NULL;
pS->pTop = pS->pBottom = pNew;
}
int main(void)
{
STACK S;
init(&S);
push(&S, 11);
push(&S, 22);
push(&S, 33);
traverse(&S);
int val;
while (pop(&S, &val)) {
printf("出栈成功:%d,栈内剩余:\n", val);
traverse(&S);
}
return 0;
}
output:
[root@8be225462e66 c]# gcc stack_hb.c && ./a.out
33 22 11
出栈成功:33,栈内剩余:
22 11
出栈成功:22,栈内剩余:
11
出栈成功:11,栈内剩余:
stack is empty.
标签:插法,return,pS,pTop,PSTACK,C语言,PNODE,pNew,节点 来源: https://blog.51cto.com/sndapk/2647847