栈的实现方式有两种,一种方法是使用指针,而另一种方法则是使用数组,这篇文章主要介绍了C语言中栈的两种实现方法,需要的朋友可以参考下
栈的两种实现方式
通常情况下,栈的实现方式有两种,一种方法是使用指针,而另一种方法则是使用数组。但是在调用程序时,我们没有必要知道具体使用了哪种方法。
一、顺序栈
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
|
#include<stdio.h>
#include<stdlib.h>
#define maxsize 64
//定义栈
typedef struct
{
int data[maxsize];
int top;
}sqstack,*sqslink;
//设置栈空
void Clearstack(sqslink s)
{
s->top=-1;
}
//判断栈空
int Emptystack(sqslink s)
{
if (s->top<0)
return 1;
else
return 0;
}
//进栈
int Push(sqslink s, int x)
{
if (s->top>=maxsize-1)
return 0;
else
{
s->top++;
s->data[s->top]=x;
return 1;
}
}
// 出栈
int Popstack(sqslink s)
{
int n;
if (Emptystack(s)>0)
return NULL;
else
{
n=s->data[s->top];
s->top--;
return n;
}
}
void main()
{
sqslink s1;
s1 =(sqslink) malloc ( sizeof (sqstack));
Clearstack(s1);
printf ( "%d\n" ,s1->top);
for ( int i=0; i<=10;i++)
{
Push(s1, i);
printf ( "%d is pushed into stack\n" ,i);
}
printf ( "top is point to %d\n" ,s1->top);
printf ( "\n" );
int n;
n = Popstack(s1);
printf ( "number %d is poped\n" ,n);
printf ( "top is point to %d\n" ,s1->top);
}
|
二、链式栈
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
|
#include<stdio.h>
#include<stdlib.h>
typedef struct node
{
int data;
struct node * next;
}snode,*slink;
struct Node
{
slink i;
slink n;
};
// 清空栈
void Clearstack(slink top)
{
top=NULL;
}
//判断栈是否为空
int Emptystack(slink top)
{
if (top==NULL) return 1;
else return 0;
}
// 进栈
slink Push(slink top, int x)
{
slink node = NULL;
node = (slink) malloc ( sizeof (snode));
node->data = x;
node->next = top;
top = node;
printf ( "*************************\n" );
printf ( "%d" ,top->data);
printf ( "*************************\n" );
return top;
}
// 出栈
struct Node Pop(slink top)
{
slink node = NULL;
struct Node result;
if (Emptystack(top))
{
result.i=node;
}
else
{
int n;
node = top;
top = node->next;
result.i = top;
result.n = node;
return result;
}
}
void main()
{
slink top_ = NULL;
for ( int i =0; i<10;i++)
{
top_ = Push(top_, i);
printf ( "%d is pushed in to the stack\n" ,i);
}
int e;
e = top_->data;
printf ( "top is pointint to %d\n" ,e);
printf ( "\n" );
printf ( "\n" );
printf ( "\n" );
slink node =NULL;
printf ( "*************************\n" );
struct Node result = Pop(top_);
if ((result.i)!=NULL)
{
top_ = result.i;
node = result.n;
e = top_->data;
printf ( "top is pointint to %d\n" ,e);
int e_node;
e_node = node->data;
printf ( "the node Poped 's data is pointint to %d\n" ,e_node);
free (node);
}
else
{
printf ( "stack is empty" );
}
}
|
0评论