leetcode 堆栈与队列

20 阅读1分钟

20. 有效的括号

#include <stdbool.h>
#include<stdio.h>
#include<stdlib.h>

struct stack {
    char val;
    struct stack *next;
};

struct stack *top;

struct stack *init() {
    struct stack *head = malloc(sizeof(struct stack));
    head->next = NULL;
    head->val = '\0';
    return head;
}


void push(char val) {
    struct stack *p = malloc(sizeof(struct stack));
    p->val = val;
    p->next = top;
    top = p;
}

char pop() {
    struct stack *p = top;
    if (p->val == '\0') return '\0';
    char ret = p->val;
    top = top->next;
    free(p);
    return ret;
}

bool isValid(char *s) {
    top = init();
    int i = 0;
    char p = s[i];
    while (p != '\0') {
        if (p == '(' || p == '{' || p == '[') {
            push(p);
        } else if (p == ')' || p == '}' || p == ']') {
            if (p == ')' && pop(top) != '(') return false;
            if (p == '}' && pop(top) != '{') return false;
            if (p == ']' && pop(top) != '[') return false;
        }
        i++;
        p = s[i];
    }
    if (top->val != '\0') return false;
    while (top != NULL) {
        struct stack *p = top;
        top = top->next;
        free(p);
    }
    return true;
}


int main() {
    const char *s = "()[]{}[";
    bool res = isValid(s);
    printf("%s \t %d\n", s, res);
    return 0;
}

image.png

844. 比较含退格的字符串

232. 用栈实现队列

class MyQueue(object):

    def __init__(self):
        self.s1=[]
        self.s2=[]

    def push(self, x):
        """
        :type x: int
        :rtype: None
        """
        self.s1.append(x)
        

    def pop(self):
        """
        :rtype: int
        """
        if not self.s1 and not self.s2:
            return None
        if self.s2:
            return self.s2.pop()
        while(self.s1):
            self.s2.append(self.s1.pop())
        return self.s2.pop()
        

    def peek(self):
        """
        :rtype: int
        """
        if self.s2:
            return self.s2[len(self.s2)-1]
        while(self.s1):
            self.s2.append(self.s1.pop())
        return self.s2[len(self.s2)-1]

    def empty(self):
        """
        :rtype: bool
        """
        return not self.s1 and not self.s2
        

225. 用队列实现栈