码迷,mamicode.com
首页 > 其他好文 > 详细

5 线性表-栈-链式存储

时间:2017-07-30 14:48:53      阅读:125      评论:0      收藏:0      [点我收藏+]

标签:data   printf   pac   main   pop   空间   链式   incr   count   

头大……

栈是一种功能受限的线性表

1、基本功能实现

  1 #include<stdio.h>
  2 #include<stdlib.h>
  3 #include<iostream>
  4 using namespace std;
  5 #define TRUE 1
  6 #define FALSE 0
  7 #define OK 1
  8 #define ERROR 0
  9 #define OVERFLOW -2
 10 #define STACK_INIT_SIZE 100//存储空间的初始分配量
 11 #define STACKINCREMENT 10//存储空间分配增量
 12 
 13 typedef int Status;
 14 typedef int Selemtype;
 15 typedef struct node
 16 {
 17     int data;
 18     struct node *next;
 19 } Stack;
 20 
 21 
 22 Status IsEmpty(Stack *s)
 23 {
 24     if(s->next==NULL)
 25     {
 26         return TRUE;
 27     }
 28     return FALSE;
 29 }
 30 void InitStack(Stack *s)
 31 {
 32     s->next=NULL;//将栈顶设为空
 33 }
 34 int Push(Stack *s,Selemtype e)
 35 {
 36     //创造新的节点 存放传入的e
 37     Stack *p;
 38     p=(Stack*)malloc(sizeof(Stack));
 39     if(p==NULL)
 40     {
 41         return 0;
 42     }
 43     p->data=e;
 44     p->next=s->next;
 45     s->next=p;
 46     return OK;
 47 }
 48 Status Pop(Stack *top,Selemtype &e)
 49 {
 50     if(IsEmpty(top)) return 0;
 51     Stack *p;
 52     p=top->next;//栈顶下面第一个节点是要出栈的
 53     e=p->data;
 54     top->next=p->next;//栈内元素的前移
 55     free(p);
 56     return OK;
 57 }
 58 void travelStack(Stack *s)
 59 {
 60     Stack *p=s->next;
 61      printf("the elemet in the stack:\n");
 62     while(p)
 63     {
 64         printf("%d ",p->data);
 65         p=p->next;
 66     }
 67 }
 68 int StackLength(Stack *s)
 69 {
 70     Stack *p=s->next;
 71     int countt=0;
 72     while(p)
 73     {
 74         countt++;
 75         p=p->next;
 76     }
 77     return countt;
 78 }
 79 void ClearStack(Stack *s)
 80 {
 81     int x;
 82     while(Pop(s,x))
 83     {
 84         printf("%d ",x);
 85     }
 86     cout<<endl;
 87     free(s);
 88 }
 89 
 90 
 91 int main()
 92 {
 93     int a;
 94     Stack *top=(Stack*)malloc(sizeof(Stack));//生成一个栈顶指针
 95     InitStack(top);
 96     int c=5;
 97     while(c--)
 98     {
 99         cin>>a;
100         Push(top,a);
101     }
102     travelStack(top);
103     cout<<endl;
104 
105     int x;
106     Pop(top,x);
107     cout<<"The ele that you delete is "<<x<<" ."<<endl;
108     x=StackLength(top);
109     cout<<x;
110     cout<<endl;
111     cout<<"Now pop all the data and clear the stack:"<<endl;
112     ClearStack(top);
113     return 0;
114 }

 

5 线性表-栈-链式存储

标签:data   printf   pac   main   pop   空间   链式   incr   count   

原文地址:http://www.cnblogs.com/AKsnoopy/p/7258999.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!