zoukankan      html  css  js  c++  java
  • C++链栈基本操作

     1 #include <iostream>
     2 using namespace std;
     3 
     4 struct Node
     5 {
     6     int data;
     7     Node *next;
     8 };
     9 
    10 /*初始化链栈*/
    11 void InitChainStack(Node *top)
    12 {
    13     top->next=0;
    14 }
    15 
    16 /*往栈里压进数据elem*/
    17 int Push(Node *top, int elem)
    18 {
    19     Node *p=(Node*)malloc(sizeof(Node));
    20     if(p==0)
    21         return false;
    22     p->data=elem;
    23     p->next = top->next;
    24     top->next=p;
    25     return true;
    26 }
    27 
    28 /*出栈,并用x返回出栈值*/
    29 int Pop(Node *top, int &x)
    30 {
    31     Node *temp = top->next;    
    32     if(temp==0)
    33         return false;
    34     top->next = temp->next;
    35     x=temp->data;
    36     free(temp);
    37     return true;
    38 }
    39 
    40 /*返回栈顶数据*/
    41 int GetTop(Node * top, int &x)
    42 {
    43     if(top->next==0)
    44         return false;
    45     x=top->next->data;
    46     return true;
    47 }
    48 
    49 /*判断栈是否为空*/
    50 int IsEmpty(Node * top)
    51 {
    52     if(top->next==0)
    53         return true;
    54     return false;
    55 }
    56 
    57 /*打印栈所有数据元素*/
    58 void PrintStack(Node *top)
    59 {
    60     Node *temp = top->next;
    61     while(temp!=0)
    62     {
    63         cout << temp->data << " ";
    64         temp=temp->next;
    65     }
    66     cout << endl;
    67 }
    68 
    69 void main()
    70 {
    71     Node *node=new Node;
    72     InitChainStack(node);
    73     
    74     for(int i=0;i<10;i++)
    75         Push(node,i);
    76     int x=0;
    77     Pop(node,x);
    78     GetTop(node,x);
    79     cout << x << endl;
    80     cout << IsEmpty(node) << endl;
    81     PrintStack(node);
    82 }
  • 相关阅读:
    03-HTML之body标签
    02-HTML之head标签
    01-HTML介绍
    第十五章 并发编程
    第十四章 网络编程
    第十三章 模块和包
    第十二章 异常和错误
    第十一章 面向对象进阶
    第九章 常用模块(续)
    003 配置负载均衡
  • 原文地址:https://www.cnblogs.com/xxdfly/p/4381119.html
Copyright © 2011-2022 走看看