Day 18: Queues and Stacks(回文字符串)

题目:

 

C++:

#include <stdlib.h>
#include <stdio.h>
#include <vector>
#include <stack>
#include <queue>
#include <map>
#include <algorithm>
#include <math.h>
#include <string>
#include <exception>
#include <stdexcept>
#include <iostream>

using namespace std;

class Solution {
	//Write your code here
private:
    stack<char> sta;
    queue<char> que;

public:
    void pushCharacter(char ch) {
	sta.push(ch);
    }

    void enqueueCharacter(char ch) {
	que.push(ch);
    }

    char popCharacter() {	
	char temp = sta.top();
	sta.pop();
	return temp;
    }

    char dequeueCharacter() {	
        char temp= que.front();
        que.pop();
        return temp;
    }
};

int main() {
    // read the string s.
    string s;
    getline(cin, s);

    // create the Solution class object p.
    Solution obj;

    // push/enqueue all the characters of string s to stack.
    for (int i = 0; i < s.length(); i++) {
	obj.pushCharacter(s[i]);
	obj.enqueueCharacter(s[i]);
    }

    bool isPalindrome = true;

    // pop the top character from stack.
    // dequeue the first character from queue.
    // compare both the characters.
    for (int i = 0; i < s.length() / 2; i++) {
	if (obj.popCharacter() != obj.dequeueCharacter()) {
		isPalindrome = false;

		break;
	}
    }

    // finally print whether string s is palindrome or not.
    if (isPalindrome) {
	cout << "The word, " << s << ", is a palindrome.";
    }
    else {
	cout << "The word, " << s << ", is not a palindrome.";
    }

    system("pause");
    return 0;
}

 

python:

import sys
class Solution:
    # Write your code here
    def __init__(self):
        # self.size = size
        self.stack = []
        self.top = -1
        self.front = -1
        self.rear = -1
        self.queue = []
    def pushCharacter(self, strr):
        if self.isfull_stack():
            raise Exception("stack is full")
        else:
            self.stack.append(strr)
            self.top = self.top + 1

    def popCharacter(self):
        if self.isempty_stack():
            raise Exception("stack is empty")
        else:
            self.top = self.top - 1
            last = self.stack.pop()
            return last

    def isfull_stack(self):
        # return self.top + 1 == self.size
        return 0    # 这里直接返回0,false,因为这里没有设置栈的size,所以,栈一直不为满

    def isempty_stack(self):
        return self.top == -1

    def show_stack(self):
        return self.stack

    def enqueueCharacter(self, strr):
        if self.isfull_queue():
            raise Exception("queue is full")
        else:
            self.queue.append(strr)
            self.rear = self.rear + 1

    def dequeueCharacter(self):
        if self.isempty_queue():
            raise Exception("queue is empty")
        else:
            first = self.queue.pop(0)
            self.front = self.front + 1
            return first

    def isfull_queue(self):
        # return self.rear - self.front + 1 == self.size
        return 0     # 这里直接返回0,false,因为这里没有设置栈的size,所以,栈一直不为满

    def isempty_queue(self):
        return self.rear == self.front

    def show_queue(self):
        return self.queue

# read the string s
s=input()
#Create the Solution class object
obj=Solution()

l=len(s)
# push/enqueue all the characters of string s to stack
for i in range(l):
    obj.pushCharacter(s[i])
    obj.enqueueCharacter(s[i])

isPalindrome=True
'''
pop the top character from stack
dequeue the first character from queue
compare both the characters
'''
for i in range(l // 2):
    if obj.popCharacter()!=obj.dequeueCharacter():
        isPalindrome=False
        break
#finally print whether string s is palindrome or not.
if isPalindrome:
    print("The word, "+s+", is a palindrome.")
else:
    print("The word, "+s+", is not a palindrome.")

总结:

C++:

1.栈(stack)说明与举例:

使用栈,要先包括头文件   #include<stack>

定义栈,一下形式实现

    stack<Type>s;    // 其中Type为数据类型(如int ,char,float等)

栈的主要操作:

s.push(item);//将item压入栈顶
s.pop();//删除栈顶的元素,但是不会返回
s.top();//返回栈顶的元素,但是不会删除
s.size();//返回栈中元素的个数
s.empty();//检查栈是否为空,如果为空返回ture,否则返回false;

栈操作举例:

#include<iostream>
#include<stack>
#include<queue>
using namespace std;
int  main()
{
    stack <int> s;
    int num;
    cout<<"------Test for Stack-----"<<endl;
    cout<<"Input number:"<<endl;
    while(cin>>num)
    {
        s.push(num);
    }
    cout<<"The Stack has "<<s.size()<<" number.they are:"<<endl;
    while(!s.empty())
    {
        cout<<s.top()<<" ";
        s.pop();
    }
    cout<<"\nNow the size is "<<s.size()<<endl;
    //system("Pause");
}

输出:

2.队列(queue)说明及举例:

使用队列,要先包含头文件: #include<queue>

定义队列,以如下形式实现:queue<Type>q;其中Type为数据类型(如Int,float,char等)

队列的主要操作:

q.push(item)//将item压入队列尾部
q.pop();//删除队尾首元素,但不返回
q.front();//返回队首元素,但不删除
q.back();//返回队尾元素,但不删除
q.size();//返回队列中元素的个数
q.empty();//检查队列是否为空,如果为空返回ture,否则返回false

队列操作举栗:

#include<iostream>
#include<stack>
#include<queue>
using namespace std;
int  main()
{
    queue<int>q;
    int num;
    cout<<"------Test for Queue-----"<<endl;
    cout<<"Input number:"<<endl;
    while(cin>>num)
    {
        q.push(num);
    }
    cout<<"Now the Queue has "<<q.size()<<" number."<<endl;
    cout<<"The first is "<<q.front()<<endl;
    cout<<"The last is "<<q.back()<<endl;
    cout<<"All numbers: "<<endl;
    while(!q.empty())
    {
        cout<<q.front()<<" ";
        q.pop();
    }
    cout<<"\nNow the Queue is "<<q.size()<<" number."<<endl;
    //system("Pause");
}

结果:

python:

Python的内置List数据结构 实现栈和队列操作的方法:

栈:

letters = []

# Let's push some letters into our list
letters.append('c')  
letters.append('a')  
letters.append('t')  
letters.append('g')

# Now let's pop letters, we should get 'g'
last_item = letters.pop()  
print(last_item)

# If we pop again we'll get 't'
last_item = letters.pop()  
print(last_item)

# 'c' and 'a' remain
print(letters) # ['c', 'a']  

执行结果:

g
t
['c', 'a']

队列:

fruits = []

# Let's enqueue some fruits into our list
fruits.append('banana')  
fruits.append('grapes')  
fruits.append('mango')  
fruits.append('orange')

# Now let's dequeue our fruits, we should get 'banana'
first_item = fruits.pop(0)  
print(first_item)

# If we dequeue again we'll get 'grapes'
first_item = fruits.pop(0)  
print(first_item)

# 'mango' and 'orange' remain
print(fruits) # ['c', 'a']  

执行结果:

banana
grapes
['mango', 'orange']

比较全面的栈和队列:

一:利用Python实现栈的功能:

class Stack(object):
    def __init__(self, size):
        self.size = size
        self.stack = []
        self.top = -1
 
    def push(self, x):
        if self.is_full():
            raise Exception("Stack Is Full")
        else:
            self.stack.append(x)
            self.top += 1
 
    def pop(self):
        if self.is_empty():
            raise Exception('Stack Is Empty')
        else:
            self.stack.pop()
            self.top -= 1
 
    def show(self):
        print(self.stack)
 
    def is_full(self):
        return self.top + 1 == self.size
 
    def is_empty(self):
        return self.top == -1
 
S = Stack(15)
for i in range(10):
    S.push(i)
S.show()
for i in range(5):
    S.pop()
S.show()

二.利用Python实现队列的功能:

class Queue(object):
    def __init__(self, size):
        self.size = size
        self.queue = []
        self.front = -1
        self.end = -1
 
    def in_queue(self, x):
        if self.is_full():
            raise Exception('Queue Is Full')
        else:
            self.queue.append(x)
            self.end += 1
 
    def out_queue(self):
        if self.is_empty():
            raise Exception('Queue Is Empty')
        else:
            self.queue.pop(0)
            self.front += 1
 
    def is_full(self):
        return (self.end - self.front + 1) == self.size
 
    def is_empty(self):
        return self.front == self.end
 
    def show(self):
        print(self.queue)
 
Q = Queue(15)
for i in range(10):
    Q.in_queue(i)
Q.show()
for i in range(5):
    Q.out_queue()
Q.show()

 

参考:https://blog.csdn.net/yinhangxitong36/article/details/80010237

           https://yq.aliyun.com/articles/689102

 

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值