棧的基本操作及其應用


這里順序棧和鏈棧的基本操作和差別在之前的線性表操作中是一樣的,目前棧對我而言在實際使用中使用哪一種差別並沒有很大,順序棧用起來會方便一點

順序棧

>>ADT:

 

typedef struct
{
    DataType data[StackSize];
    int top;//棧頂位置,棧頂元素在數組中的下標 
}SeqStack;

 

>>入棧:

int Push(SeqStack *S, DataType x)
{
    if (S->top==StackSize-1) return 0;
    S->data[++S->top] = x;
    return 1;
}

>>出棧:

int Pop(SeqStack *S, DataType *ptr)
{
    if (S->top==-1) return 0;//表示棧空的情況
    *ptr = S->data[S->top--];
    return 1; 
}

鏈棧

>>入棧:

void Push(Node *top, DataType x)
{
    Node *s = (Node*)malloc(sizeof(Node));
    s->data = x;
    s->next = top;
    top = s;
}

>>出棧:

int Pop(Node *top, DataType *ptr)
{
    if (top==NULL) return 0;//top==NULL表示空棧
    *ptr = top->data;
    top = top->next;
    free(p);
    return 1; 
}

棧的應用

1. 進制轉化

 思路:用短除法(具體原理可以去看數學證明)求余數時,結果要逆序輸出,利用棧的先進后出特點可以滿足這個要求

#include <cstdio>
#include <stack>
using namespace std;
int main()
{
    int num, d;
    scanf("%d%d", &num, &d);
    stack<int> s;
    while (num>0) {
        int x = num%d;
        s.push(x);
        num = num/d;
    }
    while (!s.empty()) {
        printf("%d", s.top());
        s.pop();
    }
    
    return 0;
}

2. 括號匹配

#include <cstdio>
#include <stack>
using namespace std;
int main()
{
    char str[1000];
    gets(str);
    stack<int> s;
    for(int i = 0; str[i]!='\0'; i++) {
        if (str[i]=='('||str[i]=='['||str[i]=='{')
            s.push(str[i]);
        else if (str[i]==')'||str[i]==']'||str[i]=='}'){
            if(s.empty()) {
                printf("No");
                return 0;
            }
            else {
                int x = s.top();
                if (x=='('&&str[i]==')'||x=='['&&str[i]==']'||x=='{'&&str[i]=='}')
                    s.pop();
                else {
                    printf("No");
                    return 0;
                }            
            }    
        }
    }
    
    if (s.empty()) printf("Yes");
    else printf("No");
    
    return 0;
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM