棧的建立、入棧、出棧、統計長度
阿新 • • 發佈:2019-02-19
C++實現,採用連結串列儲存,因為順序儲存較為簡單,不再重複敘述。
#include <iostream>
using namespace std;
struct node //棧的節點
{
int data;
struct node *next;
};
struct linkStack
{
struct node *top; //指向棧頂節點
int lengthStack; //棧長度
};
//建立一個空棧
void create(struct linkStack *S)
{
S->top = NULL ;
S->lengthStack = 0;
}
//入棧資料num
void stackInsert(struct linkStack *S, int num)
{
struct node *p = new node;
p->data = num;
if(S->top == NULL) //當棧為空時
S->top = p;
else //當棧不為空時
{
p->next = S->top;
S->top = p;
}
S-> lengthStack++;
}
//出棧並打印出棧的資料
void stackPop(struct linkStack *S)
{
struct node *temp;
if(S->top != NULL)
{
temp = S->top;
S->top = S->top->next;
cout<<temp->data<<endl;
delete(temp);
S->lengthStack--;
}
}
int main()
{
linkStack S;
create(& S);
/********入棧*************/
stackInsert(&S, 1);
stackInsert(&S, 2);
stackInsert(&S, 3);
stackInsert(&S, 4);
/********出棧*************/
stackPop(&S);
stackPop(&S);
stackPop(&S);
stackPop(&S);
return 0;
}