棧是一種僅限於在頭尾操作的數據結構,和隊列相反,棧的特點是“先進後出”,因此又稱爲LIFO。
和隊列一樣,棧也有鏈表和數組兩種實現方式,各自的優缺點和介紹隊列時提到的基本相同。以下介紹使用鏈表實現棧的方式(鏈式棧)。下面是鏈式棧的示意圖:
因爲棧的特點是“先進後出”,因此我們只需要一個指針指示棧頂即可,因爲無論插入或者刪除都是針對頂部的節點而已,也就是說,我們需要實現一個“頭節點”會變化的鏈表,並且每次變化後都可以拿到頭節點最新地址即可。
明確了這一點後,只需要在單鏈表的基礎上稍稍改進即可實現基本的棧和對應的操作。
下面是利用單鏈表實現棧的源碼:
#include <string.h>
#include <malloc.h>
#include <iostream>
using namespace std;
typedef struct stack{
int data;
struct stack* nextNode;
}stack_t;
static stack_t* s;
void stack_Init(stack_t** top){
/*
*/
}
bool stack_push(stack_t** top, int data){
stack_t* node = (stack_t*)malloc(sizeof(stack_t));
if(!node){
return false;
}
node->data = data;
node->nextNode = *top;
*top = node;
return true;
}
bool isEmpty(stack_t* top){
return (top == NULL);
}
bool stack_pop(stack_t** top){
if(isEmpty(*top)){
return false;
}
stack_t* tmp = *top;
*top = (*top)->nextNode;
if(tmp){
free(tmp);
}
return true;
}
void printStackData(stack_t* top){
stack_t* tmp = top;
while(tmp){
cout << tmp->data << " ";
tmp = tmp->nextNode;
}
cout << endl;
}
void stack_Deinit(stack_t** top){
stack_t* tmp = *top;
while(tmp){
cout << "free node, data is:" << tmp->data << endl;
free(tmp);
*top = (*top)->nextNode;
tmp =*top;
}
}
bool topValue(stack_t* top, int& val){
if(isEmpty(top)){
return false;
}
val = top->data;
return true;
}
int main(){
stack_t* s = NULL;
stack_push(&s,1);
stack_push(&s,2);
int val;
if(topValue(s, val))
cout << "now top value of stack is:" << val << endl;
stack_push(&s,3);
printStackData(s);
stack_pop(&s);
printStackData(s);
stack_push(&s,100);
stack_push(&s,201);
if(topValue(s, val))
cout << "now top value of stack is:" << val << endl;
stack_push(&s,303);
printStackData(s);
stack_Deinit(&s);
printStackData(s);
cout << "stack empty? " << isEmpty(s) << endl;
}