用链表模拟栈(100)

来源:互联网 发布:灵格斯翻译家 for mac 编辑:程序博客网 时间:2024/06/12 23:59

源代码:

//目的:利用链表模拟栈 #include <stdio.h>#include <stdlib.h>typedef struct node {int data;struct node *next;} Stacknode;Stacknode *Init (Stacknode *top) {top = NULL;return top;}int not_empty (Stacknode *top) {    return top != NULL;}Stacknode *Push (Stacknode *top, int x) {Stacknode *p;p = (Stacknode*)malloc(sizeof(Stacknode));if (p == NULL)    return p;else {p->data = x;p->next = top;top = p;return top;}}Stacknode *Pop (Stacknode *top, int *x) {Stacknode *p;if (top == NULL)    return top;else {    *x = top->data;    p = top;    top = top->next;free(p);return top;    }}int main() {Stacknode p, *top, *l;top = &p;int a,b,i;top = Init (top);while (1) {printf("\n1.Input a stack data\n");printf("\n2.Output a stack data\n");printf("\n3.Exit\n");printf("Please select one->");scanf("%d",&a);if (a == 3)    break;switch(a) {case 1:    printf("\nPlease input the data->");    scanf("%d",&b);    top = Push(top, b);    l = top;    printf("\nthe elements are:\n");                while(l != NULL) {                    printf("%d ", l->data);                    l = l->next;} break;case 2:if (top != NULL) {top = Pop(top, &b);l = top;                    while(l != NULL) {                        printf("%d ", l->data);                        l = l->next;    } }else    printf("\nStack is empty\n");break;}}return 0;}

运行结果:


0 0
原创粉丝点击