数据结构 -- 用C实现链式栈

    xiaoxiao2021-03-25  56

    #include <stdio.h> #include <stdlib.h> struct node { int data; struct node *next; }Stack; int gettop(struct node *top) { return top -> data; } struct node * push(struct node *top,int x ) { struct node *p; p = (struct node *)malloc(sizeof(struct node)); p->data = x; p->next = top; top = p; return top; } struct node * pop(struct node *top) { struct node *p; if(!top) return NULL; p = (struct node *)malloc(sizeof(struct node)); p = top; top = top->next; free(p); return top; } int stempty(struct node *top) { return(top->next==NULL ? 0 : 1); } int main() //用于测试 { struct node *top; int n; //栈的长度 top = (struct node *)malloc(sizeof(struct node)); top->next = NULL; int a[6] = {1,2,3,4,5,6},t = 7;//测试数据 int i; for(i=0; i<6; i++) { top = push(top,a[i]); } top = push(top,t); top = pop(top); top = pop(top); printf("%d\n",gettop(top)); while(top->next !=NULL) { printf("%d ",top->data); printf("%d\n",stempty(top)); top=top->next; } printf("%d\n",stempty(top)); return 0; }
    转载请注明原文地址: https://ju.6miu.com/read-33081.html

    最新回复(0)