C++学习笔记49:栈

栈是一种只能从一端访问的线性数据结构,栈是一种后进先出的数据结构

//stack.h
#ifndef STACK_H
#define STACK_H
#include <cassert>
template <class T, int SIZE = > class Stack
{
private:
T list[SIZE];
int top;
public:
Stack();
void push(const T &item);
T pop();
void clear();
const T &peek() const;
bool isEmpty() const;
bool isFull() const;
}; //模板的实现
template <class T, int SIZE>
Stack<T, SIZE>::Stack():top(-){} template <class T, int SIZE> void Stack<T, SIZE>::push(const T &item)
{
assert(!isFull());
list[++top] = item;
} template <class T, int SIZE> T Stack<T, SIZE>::pop() const
{
assert(!isEmpty());
return list[top--];
} template <class T, int SIZE> const T &Stack<T, SIZE>::peek() const
{
assert(!isEmpty());
return list[top];
} template <class T, int SIZE> bool Stack<T, SIZE>::isEmpty() const
{
return top == -;
} template <class T, int SIZE> bool Stack<T, SIZE>::isFull() const
{
return top == SIZE - ;
} template <class T, int SIZE> void Stack<T, SIZE>::clear()
{
top = -;
} #endif //

栈的引用:判断是否存在不匹配的()

#include <iostream>
#include <string>
#include <cassert>
using namespace std; template <class T, int MAX = > class Stack
{
private:
T list[MAX + ];
int top;
public:
Stack();
void push(const T &item);
T pop();
const T & peek() const;
bool isEmpty() const;
}; template <class T, int MAX> Stack<T, MAX>::Stack() :top(-)
{ } template <class T, int MAX> void Stack<T, MAX>::push(const T &item)
{
if (top != MAX - )
{
list[++top] = item;
}
} template <class T, int MAX> bool Stack<T, MAX>::isEmpty() const
{
return top == -;
} template <class T, int MAX> T Stack<T, MAX>::pop()
{
assert(!isEmpty());
return list[top--];
} template <class T, int MAX> const T &Stack<T, MAX>::peek() const
{
assert(!isEmpty());
return list[top];
} void judgeBrackets(string str)
{
Stack<char>p;
int k = ;
int count = ;
while (str[k] != '\0')
{
if (str[k] == '(')
{
p.push(str[k]);
count++;
}
if (str[k] == ')')
{
if (count == )
{
cout << "NO" << endl;
count--;
break;
}
else
{
p.pop();
count--;
}
}
k++;
}
if (count == )
cout << "Yes" << endl;
if (count > )
cout << "NO" << endl;
} int main()
{
string str;
while (cin >> str)
{
judgeBrackets(str);
}
}
上一篇:全国计算机等级考试二级教程-C语言程序设计_第3章_顺序结构


下一篇:Power Designer导出实体类和NHibernate xml文件