棧的鏈式儲存結構(c語言實現)
阿新 • • 發佈:2019-01-04
#include <stdio.h> #include <stdlib.h> #define T 1 #define F 0 typedef int Status; typedef int ElemType; typedef struct StackNode//鏈式儲存的結點 { ElemType data;//資料域 struct StackNode* next;//指標域 }StackNode, *LinkStackPtr; typedef struct LinkStack//棧 { LinkStackPtr top;//top即棧頂 放在單鏈表的頭部,對於鏈棧來說不需要頭結點 int count;//棧的長度 }LinkStack; void init(LinkStack* S); Status push(LinkStack* S, ElemType e); Status pop(LinkStack* S, ElemType* e); Status stackEmpty(LinkStack S); int main() { int i = 0, num = 0; LinkStack S; init(&S); for (; i < 10; i++) { push(&S, i); } for (; i > 0; i--) { pop(&S, &num); printf("%d\n", num); } return 0; } void init(LinkStack* S)//初始化為空棧 { S->top = NULL; S->count = 0; } Status push(LinkStack* S, ElemType e) { //和連結串列一樣正常建立結點 LinkStackPtr s = (LinkStackPtr)malloc(sizeof(StackNode)); s->data = e; s->next = S->top;//往上入棧 S->top = s; S->count++; return T; } Status pop(LinkStack* S, ElemType* e) { LinkStackPtr p; if (stackEmpty(*S))//S是地址 要傳值 { return F; } *e = S->top->data; p = S->top; S->top = S->top->next; free(p);//釋放出棧結點 S->count--; return T; } Status stackEmpty(LinkStack S) { if (0 == S.count) { return T; } else { return F; } }
執行結果:
另一種簡便表示:
#include <stdio.h> #include <stdlib.h> #define T 1 #define F 0 typedef struct Node { int value; struct Node *next; }Node; typedef struct { Node *top; int count; }Stack; int init(Stack *s); int push(Stack *s, int e); int pop(Stack *s, int *e); int main() { int i, e; Stack s; init(&s); for (i = 0; i < 5; i++) { push(&s, i); pop(&s, &e); printf("%d\n", e); } return 0; } int init(Stack *s) { s->top = NULL;//初始化為空棧 s->count = 0; return T; } int push(Stack *s, int e) { Node *newNode = (Node*)malloc(sizeof(Node)); if (NULL == newNode) { return F; } newNode->next = s->top; newNode->value = e; s->top = newNode; s->count ++; return T; } int pop(Stack *s, int *e) { Node *temp = NULL; if (0 == s->count) { return F; } temp = s->top; *e = temp->value; s->top = temp->next; free(temp); s->count --; return F; }
執行結果: