zoukankan      html  css  js  c++  java
  • 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 }

    以下是运行结果:

  • 相关阅读:
    数据结构最小生成树两个算法
    hdu-1742Ellipse(自适应辛普森)
    hdu1251统计难题
    codeforces-551C GukiZ hates Boxes
    CodeForces
    codeforces-894C Marco and GCD Sequence
    codeforces-892B Wrath
    codeforces-894B Ralph And His Magic Field
    CodeForces
    CodeForces
  • 原文地址:https://www.cnblogs.com/hymhblf/p/3216080.html
Copyright © 2011-2022 走看看