zoukankan      html  css  js  c++  java
  • 数据结构-链栈

     1 #include <iostream>
     2 #include <stdlib.h>
     3 using namespace std;
     4 
     5 typedef struct LNode
     6 {
     7     int data;
     8     struct LNode *next;
     9 }LNode;//栈结点定义
    10 
    11 void InitStack(LNode *&S)
    12 {
    13     S=(LNode*)malloc(sizeof(LNode));
    14     S->next=NULL;
    15 }
    16 
    17 int IsEmpty(LNode *S)
    18 {
    19     if(S->next==NULL)
    20         return 1;
    21     else
    22         return 0;
    23 }
    24 
    25 void Push(LNode *&S,int e)
    26 {
    27     LNode *p;
    28     p=(LNode*)malloc(sizeof(LNode));
    29     p->next=NULL;
    30     p->data=e;
    31 
    32     p->next=S->next;
    33     S->next=p;
    34 }
    35 
    36 int Pop(LNode *&S,int &e)
    37 {
    38     LNode *p;
    39     if(S->next==NULL)
    40         return 0;
    41 
    42     p=S->next;
    43     e=p->data;
    44     S->next=p->next;
    45     free(p);
    46     return 1;
    47 }
    48 
    49 void Print(LNode *S)
    50 {
    51     if(S->next==NULL)
    52     {
    53         cout<<"链栈为空! "<<endl;
    54         return;
    55     }
    56     LNode *p;
    57     p=S->next;
    58     cout<<"
    链栈中的元素为(栈顶->栈底):
    ";
    59     while(p!=NULL)
    60     {
    61         cout<<"  "<<p->data<<"  ";
    62         p=p->next;
    63     }
    64     return;
    65 }
    66 
    67 int main()
    68 {
    69     int i,e;
    70     LNode *S;
    71     InitStack(S);
    72     for(i=0;i<10;++i)
    73         Push(S,i);
    74     Print(S);
    75 
    76 
    77     cout<<"
    
    依次出栈的四个元素为:
    ";
    78     for(i=0;i<4;++i)
    79     {
    80         Pop(S,e);
    81         cout<<"  "<<e<<"  ";
    82     }
    83     //cout<<"
    
    ";
    84     Print(S);
    85     if(IsEmpty(S)==1)
    86         cout<<"
    此时,链栈为空!
    ";
    87     else
    88         cout<<"
    此时,链栈非空!
    ";
    89 
    90     return 0;
    91 }
  • 相关阅读:
    JAVA的HashTable源码分析
    散列表
    JAVA的HashSet源码分析
    Java中HashMap源码分析
    MySQL max_allowed_packet设置及问题
    通过分析 JDK 源代码研究 TreeMap 红黑树算法实
    红黑树详解
    TreeMap源码分析
    Vector的浅析
    web.xml 配置中classpath: 与classpath*:的区别
  • 原文地址:https://www.cnblogs.com/Xbert/p/5087755.html
Copyright © 2011-2022 走看看