http://blog.csdn.net/jwentao01/article/details/46765517###;
棧基本概念:?
棧(stack)是限定在表尾進行插入和刪除操作的線性表(或單鏈表)。?
//只能在一段進行插入和刪除,因此不存在,在中間進行插入?
棧頂(top):允許插入和刪除的一端。而另一端稱為棧底(bottom)?
空棧:不含任何數據元素的棧。?
后進先出
兩個基本操作:?
棧的插入操作(push),叫做進棧,或壓棧,或入棧?
刪除操作(pop),叫做出棧,或彈棧?
注意鏈棧next指針的指向,與隊列不同:?
如果插入一個元素,它的next指針是指向前一個已經在棧中的元素的?
而隊列則是,插入一個元素,其next指針是往外指,指向空。?
鏈棧的next指針之所以這樣,是方便刪除操作,這一點可以在編程的過程中體會到。?
以下是代碼:
#include <iostream>using namespace std;typedef struct node{int data;struct node *next;
}Node;typedef struct stack{Node *top; /**書本寫法是:加一個bottom,個人感覺沒什么用,反而加一個count用于表示節點數會更好*/int count;
}Link_Stack;/**創建一個空棧*/
Link_Stack * Creat_stack()
{Link_Stack *p;p = new Link_Stack; /**這一步不要忘!需要給p創建空間*/p->count = 0;p->top = NULL;return p;
}/**入棧操作:push*/
Link_Stack * Push_stack(Link_Stack *p,int elem)
{if(NULL == p)return NULL;Node *temp;temp = new Node;temp->data = elem;temp->next = p->top; /**注意這里和隊列的入隊操作不同,next指向不同,為了方便出棧操作*/p->top = temp;p->count += 1;return p;
}/**出棧操作:pop*/
Link_Stack * Pop_stack(Link_Stack *p)
{Node *temp;temp = p->top;if(NULL == p->top){cout << "The stack is empty." << endl;return p;}else{p->top = p->top->next; /** temp = temp->next; 千萬不能這么寫,看看下一步是什么?*/delete temp;p->count -= 1;return p;}
}/**棧的遍歷:輸出棧*/
int Show_stack(Link_Stack *p)
{Node *temp;temp = p->top;if(NULL == p->top){cout << "The stack is empty." << endl;return 0;}while(NULL != temp){cout << temp->data << ' ';temp = temp->next;}cout << endl;return 0;
}int main()
{int i = 5;int elem;Link_Stack *p;p = Creat_stack();while(i--){cin >> elem;Push_stack(p,elem);}cout << "空棧插入5個元素后:" << endl;Show_stack(p);cout << "刪除3個元素后:" << endl;for(i = 3;i--;){Pop_stack(p);}Show_stack(p);cout << "count:" << p->count << endl;cout << "刪除2個元素后:" << endl;for(i = 2;i--;){Pop_stack(p);}Show_stack(p);cout << "count:" << p->count << endl;Push_stack(p,6);cout << "插入元素6后:" << endl;Show_stack(p);cout << "count:" << p->count << endl;return 0;
}
- 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
- 104
- 105
- 106
- 107
- 108
- 109
- 110
- 111
- 112
- 113
- 114
- 115
- 116
- 117
- 118
- 119
- 120
- 121
結果如下:?
/點滴積累,我的一小步O(∩_∩)O~/