C实现链表形式的栈
程序员文章站
2022-03-22 15:58:03
...
一、头文件、宏及函数声明:
#include <stdio.h> #include <stdlib.h> typedef enum status { success, overflow, underflow } Status; typedef int StackEntry; typedef struct stacknode { StackEntry entry; struct stacknode* next; } StackNode, *StackNodePtr; typedef struct stack { StackNodePtr top; } Stack, *StackPtr; Status Stack_Push(StackPtr s, StackEntry item); Status Stack_Pop(StackPtr s, StackEntry* item); StackNodePtr MakeNode(StackEntry item); StackEntry Stack_Top(StackPtr s, StackEntry* item); int Stack_Empty(StackPtr s);
二、函数实现:
Status Stack_Push(StackPtr s, StackEntry item) { Status outcome = success; StackNodePtr np = MakeNode(item); if(np == NULL) { outcome = overflow; } else { np->next = s->top; s->top = np; } return outcome; } StackNodePtr MakeNode(StackEntry item) { StackNodePtr np = (StackNodePtr)malloc(sizeof(StackNode)); np->entry = item; np->next = NULL; return np; } Status Stack_Pop(StackPtr s, StackEntry* item) { Status outcome = success; if(Stack_Empty(s)) { outcome = underflow; } else { StackNodePtr temp = s->top; s->top = temp->next; *item = temp->entry; free(temp); } return outcome; } StackEntry Stack_Top(StackPtr s, StackEntry* item) { Status outcome = success; if(Stack_Empty(s)) { outcome = underflow; } else { *item = s->top->entry; } return outcome; } int Stack_Empty(StackPtr s) { if(s->top == NULL) return 1; else return 0; }
三、测试函数:
int main(int argc, char const *argv[]) { Status s; StackPtr sp = (StackPtr)malloc(sizeof(StackPtr)); s = Stack_Push(sp, 100); if(s == success) { StackEntry* item = malloc(sizeof(StackEntry)*10); s = Stack_Top(sp, item); if(s == success) { printf("%d\n", sp->top->entry); } free(item); } free(sp); return 0; }