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 /*往棧里壓進數(shù)據(jù)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 /*返回棧頂數(shù)據(jù)*/
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 /*打印棧所有數(shù)據(jù)元素*/
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 }
?
轉(zhuǎn)載于:https://www.cnblogs.com/xxdfly/p/4381119.html
總結(jié)
- 上一篇: 【转】JavaScript eval处理
- 下一篇: 简单的线程同步问题:两个线程交替执行N次