stack note

参考 http://www.cnblogs.com/java06/archive/2012/10/16/3122428.html

1,顺序栈

定义栈:

1 #define stacksize 1000;    
2 typedef int datatype;
3 
4 struct seqstack
5 {
6     datatype data[stacksize];
7     int top;
8 };

置栈空:

1 void initstack(struct seqstack *s)
2 {
3     s -> top = -1;
4 }

判断栈空:

1 int stackempty(struct seqstack *s)
2 {
3     int flag;
4 
5     flag = (s -> top == -1)? 1 : 0; //此处未用if
6 
7     return flag;
8 }

入栈:

1 void push(struct seqstack *s,x)
2 {
3     s -> top ++;
4     if stackfull; //
5         exit("stack overflow\n");    //数组溢出
6     
7 
8     s -> data[s -> top] = x;
9 }

2,链栈

定义栈:

 1 typedef struct stacknode
 2 {
 3     datatype data;
 4     struct stacknode *next;
 5 }stacknode;
 6 
 7 typedef struct
 8 {
 9     stacknode *top;
10 }linkstack;

置空:

1 void initstack(linkstack *s)
2 {
3     s -> top = NULL;
4 }

判栈空:

1 void initstack(linkstack *s)
2 {
3     s -> top = NULL;
4 }

入栈:

1 void push(linkstack *s, datatype x)
2 {
3     struct stacknode *p;
4     p = malloc(sizeof(struct stacknode));
5     p -> data = x;
6     p -> next = s -> top;
7     s -> top = p;
8 }

出栈:

 1 datatype pop(linkstack *s)
 2 {
 3     datatype x;
 4     struct stacknode *p = s -> top;
 5     if(stackempty(s))
 6         exit("stack is empty!\n");
 7     x = p -> data;
 8     s -> top = p -> next;
 9     free(p);
10     return x;
11 }

取栈顶:

1 datatype stacktop(linkstack *s)
2 {
3     if(stackempty(s))
4         exit("stack is empty!\n");
5     return s -> top -> data;
6 }

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

posted @ 2014-05-27 01:16  voh99800  阅读(147)  评论(0编辑  收藏  举报