运行截图:
完整代码:
#include <stdio.h> #include <stdlib.h> //定义类型 #define datatype int //定义栈的结点 typedef struct stack { datatype data; struct stack *pNext; }stack, *pstack; //入栈 从尾部入,从尾部出(也可以从头部入从头部出) void push(pstack *phead, datatype data) { //创建新的结点 pstack p_new_node = (pstack)malloc(sizeof(stack)); p_new_node->data = data; p_new_node->pNext = NULL; //如果结点为NULL,第一个赋值 if (*phead == NULL) { *phead = p_new_node; } //否则循环到结点的末尾,并把结点连接上去 else { pstack ptmp = *phead; while (ptmp->pNext != NULL) { ptmp = ptmp->pNext; } ptmp->pNext = p_new_node; } } //出栈 stack *pop(pstack *phead) { if (*phead == NULL) { return NULL; } //如果只有一个结点 else if ((*phead)->pNext == NULL) { //创建结点并赋值,头结点置为空 pstack pnew = (pstack)malloc(sizeof(stack)); pnew->data = (*phead)->data; pnew->pNext = NULL; *phead = NULL; return pnew; } else { //如果大于一个结点,循环到倒数第二个节点,删除后一个 pstack ptmp = *phead; while (ptmp->pNext->pNext != NULL) { ptmp = ptmp->pNext; } //创建结点并赋值 pstack pnew = (pstack)malloc(sizeof(stack)); pnew->data = ptmp->pNext->data; pnew->pNext = NULL; //回收内存 free(ptmp->pNext); ptmp->pNext = NULL; return pnew; } } //显示链表数据 void show(pstack phead) { if (phead == NULL) { return; } else { while (phead != NULL) { printf("%4d", phead->data); phead = phead->pNext; } printf(" "); } } void main() { pstack stack1 = NULL; for (int i = 0; i < 10; i++) { printf("入栈 "); push(&stack1, i); show(stack1); } while (stack1 != NULL) { printf("出栈: "); pstack p = pop(&stack1); show(stack1); } system("pause"); }