• 链栈的实现


    stack.h

     1 #ifndef _STACK_H
     2 #define _STACK_H
     3 
     4 #include<stdio.h>
     5 #include<stdlib.h>
     6 
     7 typedef struct StackNode
     8 {
     9     int data;
    10     struct StackNode* next;
    11 }StackNode,*LinkStack;
    12 
    13 //初始化
    14 void init(LinkStack top);
    15 //判断栈是否为空
    16 int isEmpty(LinkStack top);
    17 //将一个元素压入栈
    18 int push(LinkStack top, int val);
    19 //从栈中弹出一个元素
    20 int pop(LinkStack top, int *val);
    21 //获取栈顶元素的值
    22 int getTop(LinkStack top);
    23 
    24 
    25 #endif

    stack.c

     1 #include "stack.h"
     2 
     3 void init(LinkStack top)
     4 {
     5     top->next = NULL;
     6 }
     7 
     8 int isEmpty(LinkStack top)
     9 {
    10     if(top->next == NULL)
    11         return 1;
    12     return 0;
    13 }
    14 //top指向的结点为空的头结点
    15 int push(LinkStack top, int val)
    16 {
    17     StackNode *newNode;
    18     newNode = (StackNode*)calloc(1,sizeof(StackNode));
    19     newNode->data = val;
    20 
    21     if(newNode == NULL)
    22         return 0;
    23     newNode->next = top->next;
    24     top->next = newNode;
    25     return 1;
    26 }
    27 
    28 
    29 int pop(LinkStack top, int *val)
    30 {
    31     StackNode *oldNode;
    32     if(isEmpty(top))
    33     {
    34         printf("The stack is empty!
    ");
    35         return 0;
    36     }
    37     oldNode = top->next;
    38     //记录栈顶元素的值
    39     *val = oldNode->data;
    40     top->next = oldNode->next;
    41     //释放
    42     free(oldNode);
    43     return 1;
    44 }
    45 
    46 int getTop(LinkStack top)
    47 {
    48     return top->next->data;
    49 }

    main.c

     1 #include "stack.h"
     2 
     3 int main()
     4 {
     5     LinkStack top;
     6     top = (StackNode*)malloc(sizeof(StackNode));
     7     int val, index;
     8     init(top);
     9 
    10     //向栈中压入一系列元素
    11     for(index = 0; index < 12; index++)
    12         push(top,index);
    13 
    14     //获取栈顶元素
    15     val = getTop(top);
    16     printf("栈顶元素为:%d
    ",val);
    17 
    18 
    19     //弹出栈中元素
    20     printf("依次弹出栈顶元素:
    ");
    21     while(!(isEmpty(top)))
    22     {
    23         pop(top,&val);
    24         printf("->%2d",val);
    25     }
    26     printf("
    ");
    27     return 0;
    28 }

     运行结果:

  • 相关阅读:
    MySQL错误:The user specified as a definer (XXX@XXX) does not exist (1449错误)最简解决方案
    个人亲测,在win10系统下安装多实例mysql详细教程
    Quartus II 9.1 + ModelSim-Altera 6.5b
    MathType Translation Error
    从txt文件中读取数据放在二维数组中
    VMware Player安装Debian系统
    linux下JDK安装
    Vector、HashTable、HashMap和ConcurrentHashMap
    线程池策略(一)
    Runnable、Callable和Future
  • 原文地址:https://www.cnblogs.com/cpsmile/p/4428583.html
Copyright © 2020-2023  润新知