225. Implement Stack using Queues(用队列模拟栈)

题目

Implement the following operations of a stack using queues.

  • push(x) – Push element x onto stack.
  • pop() – Removes the element on top of the stack.
  • top() – Get the top element.
  • empty() – Return whether the stack is empty.

Notes:

  • You must use only standard operations of a queue – which means only push to back, peek/pop from front, size, and is empty operations are valid.
  • Depending on your language, queue may not be supported natively. You may simulate a queue by using a list or deque (double-ended queue), as long as you use only standard operations of a queue.
  • You may assume that all operations are valid (for example, no pop or top operations will be called on an empty stack).

题意

用队列实现栈的操作。

  • push(x) – 进栈.
  • pop() – 出战.
  • top() – 获取栈顶元素.
  • empty() – 判断栈是否为空.

Notes:

  • 您必须只使用队列的标准操作——这意味着只有从前到后、从前端到大小,以及空操作都是有效的。.
  • 这取决于你的语言,可能不支持本地队列。你可以通过使用列表或队列模拟一个队列(双端队列),只要你只使用一个队列的标准操作.
  • 您可以假设所有操作都是有效的(例如,在空堆栈上不会调用POP或顶级操作)。 .

题解

queue 的基本操作有:

操作说明
q.push(x)入队, 将x 接到队列的末端
q.pop()出队,弹出队列的第一个元素,注意,并不会返回被弹出元素的值
q.front()访问队首元素, 即最早被压入队列的元素。
q.back()访问队尾元素, 即最后被压入队列的元素
q.empty()判断队列空,, 当队列空时,返回true
q.size()访问队列中的元素个数

栈的特点是:先进后出
队列的特点是:先进先出
思路:把队列中的元素转换成栈操作的顺序
例如 :
栈中 1 2 3,出栈为 3 2 1
队列中1 2 3, 出队 1 2 3
如果队列中元素为 3 2 1, 出队3 2 1
如何转换:
每在队列中添加一个元素,转换一次,具体见代码

C++代码
class MyStack {
public:
    /** Initialize your data structure here. */
    queue<int>q;
    queue<int>temp;

    MyStack() {

    }

    /** Push element x onto stack. */
    void push(int x) {
        q.push(x);
        for(int i=0; i<q.size()-1; i++)//把前n-1个依次放在队尾
        /*
        例如 队列中现在的元素为 1 2
        添加元素3 为 3 1 2
        将前2个元素依次放在队尾
        即1 2 3
        */
        {
            q.push(q.front());
            q.pop();
        }
    }

    /** Removes the element on top of the stack and returns that element. */
    int pop() {

        int m = q.front();
        q.pop();
        return m;
    }


    /** Get the top element. */
    int top() {
        return q.front();
    }

    /** Returns whether the stack is empty. */
    bool empty() {
        return q.empty();
    }
};

python代码

python中的队列的详细用法:
https://www.cnblogs.com/cmnz/p/6936181.html
http://python.jobbole.com/87577/

from collections import deque
class MyStack:

    def __init__(self):
        self.q = deque();

    def push(self, x):
        self.q.append(x)
        for i in range(0, len(self.q)-1):
            self.q.append(self.q.popleft())
        #q.popleft()删除栈顶元素并返回此元素值

    def pop(self):
        return self.q.popleft()

    def top(self):#返回栈顶元素
        return self.q[0]

    def empty(self):
        return len(self.q)==0

Dataset: Student Records We will implement stack using both array and linked list data structures to store student records. Each student record will have the following information: student name, student ID, and student GPA. 1. Stack using Array: We will use an array to implement stack data structure for storing student records. The array will have a fixed size, and we will use the push, pop, and peek operations to add, remove, and view the top element of the stack, respectively. The Java code for implementing stack using an array is given below: ``` public class StudentRecord { private String name; private int id; private double gpa; public StudentRecord(String name, int id, double gpa) { this.name = name; this.id = id; this.gpa = gpa; } // getters and setters public String toString() { return "Name: " + name + ", ID: " + id + ", GPA: " + gpa; } } public class StudentRecordStack { private StudentRecord[] stack; private int top; private int size; public StudentRecordStack(int size) { stack = new StudentRecord[size]; top = -1; this.size = size; } public void push(StudentRecord record) { if (top == size - 1) { System.out.println("Stack Overflow!"); return; } top++; stack[top] = record; } public StudentRecord pop() { if (top == -1) { System.out.println("Stack Underflow!"); return null; } StudentRecord record = stack[top]; top--; return record; } public StudentRecord peek() { if (top == -1) { System.out.println("Stack Underflow!"); return null; } return stack[top]; } public boolean isEmpty() { return top == -1; } public boolean isFull() { return top == size - 1; } } ``` To test the stack implementation, we can create a few student records and push them onto the stack: ``` public class Main { public static void main(String[] args) { StudentRecordStack stack = new StudentRecordStack(5); StudentRecord record1 = new StudentRecord("John", 1001, 3.5); StudentRecord record2 = new StudentRecord("Jane", 1002, 3.8); StudentRecord record3 = new StudentRecord("Bob", 1003, 3.2); stack.push(record1); stack.push(record2); stack.push(record3); System.out.println(stack.peek()); System.out.println(stack.pop()); System.out.println(stack.pop()); System.out.println(stack.pop()); } } ``` Output: ``` Name: Bob, ID: 1003, GPA: 3.2 Name: Bob, ID: 1003, GPA: 3.2 Name: Jane, ID: 1002, GPA: 3.8 Name: John, ID: 1001, GPA: 3.5 Stack Underflow! ``` 2. Stack using Linked List: We will use a linked list to implement stack data structure for storing student records. The linked list will have a dynamic size, and we will use the push, pop, and peek operations to add, remove, and view the top element of the stack, respectively. The Java code for implementing stack using a linked list is given below: ``` public class StudentRecordNode { private StudentRecord record; private StudentRecordNode next; public StudentRecordNode(StudentRecord record) { this.record = record; this.next = null; } // getters and setters } public class StudentRecordStack { private StudentRecordNode top; public StudentRecordStack() { top = null; } public void push(StudentRecord record) { StudentRecordNode node = new StudentRecordNode(record); node.next = top; top = node; } public StudentRecord pop() { if (top == null) { System.out.println("Stack Underflow!"); return null; } StudentRecord record = top.record; top = top.next; return record; } public StudentRecord peek() { if (top == null) { System.out.println("Stack Underflow!"); return null; } return top.record; } public boolean isEmpty() { return top == null; } } ``` To test the stack implementation, we can create a few student records and push them onto the stack: ``` public class Main { public static void main(String[] args) { StudentRecordStack stack = new StudentRecordStack(); StudentRecord record1 = new StudentRecord("John", 1001, 3.5); StudentRecord record2 = new StudentRecord("Jane", 1002, 3.8); StudentRecord record3 = new StudentRecord("Bob", 1003, 3.2); stack.push(record1); stack.push(record2); stack.push(record3); System.out.println(stack.peek()); System.out.println(stack.pop()); System.out.println(stack.pop()); System.out.println(stack.pop()); } } ``` Output: ``` Name: Bob, ID: 1003, GPA: 3.2 Name: Bob, ID: 1003, GPA: 3.2 Name: Jane, ID: 1002, GPA: 3.8 Name: John, ID: 1001, GPA: 3.5 Stack Underflow! ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值