• C语言实现线性表之栈算法


    以下为代码:

     1 # include <stdio.h>
     2 # include <malloc.h>
     3 # include <stdlib.h>
     4 
     5 typedef struct LinkList
     6 {
     7     int data;
     8     struct LinkList * next;
     9 }NODE, * PNODE;
    10 
    11 typedef struct Stact
    12 {
    13     PNODE top;
    14     PNODE pbottom;
    15 }STACK,* PSTACK;
    16 
    17 void init(PSTACK p);
    18 bool Push(PSTACK p,int val);
    19 bool Pop(PSTACK p);
    20 void Traverse(PSTACK p);
    21 bool IsEmpty(PSTACK p);
    22 
    23 int main(int argc, char *argv[])
    24 {
    25     STACK stack;
    26     init(&stack);    
    27     Pop(&stack);
    28     Push(&stack,1);    
    29     Push(&stack,2);    
    30     Push(&stack,3);    
    31     Push(&stack,4);    
    32     Push(&stack,5);    
    33     Traverse(&stack);
    34     Pop(&stack);
    35     Traverse(&stack);
    36     return 0;
    37 }
    38 void init(PSTACK p){
    39     p->top =(PNODE)malloc(sizeof(NODE));
    40     if(NULL==p->top){
    41         printf("内存分配失败");
    42         exit(-1);
    43     }
    44     p->pbottom=p->top;
    45     p->top->next=NULL;
    46 }
    47 bool Push(PSTACK p,int val){
    48     PNODE pnode=(PNODE)malloc(sizeof(NODE));
    49     if(NULL==pnode){
    50         printf("内存分配失败");
    51         return false;    
    52     }
    53     pnode->data=val;
    54     pnode->next=p->top;
    55     p->top=pnode; 
    56     return true;
    57 }
    58 bool Pop(PSTACK p){
    59     if(IsEmpty(p)){
    60         printf("栈已空
    ");
    61         return false;
    62     }
    63     PNODE pnode=p->top;
    64     p->top=p->top->next;
    65     free(pnode);
    66 }
    67 void Traverse(PSTACK p){
    68     PNODE pnode=p->top;
    69     while(pnode!=p->pbottom){
    70         printf("%d ",pnode->data);
    71         pnode=pnode->next;
    72     }
    73     printf("
    ");
    74 }
    75 bool IsEmpty(PSTACK p){
    76     if(p->top==p->pbottom)
    77     {
    78         return true;
    79     }
    80     return false;
    81 }

    以下是运行结果:

  • 相关阅读:
    RocketMQ源码 — 十、 RocketMQ顺序消息
    RocketMQ源码 — 九、 RocketMQ延时消息
    RocketMQ源码 — 八、 RocketMQ消息重试
    HDU3439 Sequence
    Cipolla算法学习小记
    BZOJ2286: [Sdoi2011]消耗战
    BZOJ4873 寿司餐厅
    BZOJ1718 [Usaco2006 Jan] Redundant Paths 分离的路径
    BZOJ1123 [POI2008]BLO
    BZOJ3996 TJOI2015线性代数
  • 原文地址:https://www.cnblogs.com/hymhblf/p/3216080.html
Copyright © 2020-2023  润新知