C/C++基本数据结构:顺序表/链表堆栈

堆栈
一、基础数据结构
1.顺序表:数组,存储在连续的空间中,随机访问方便,空间要求高,插入删除效率低。
2.链表:数据存储在不连续的节点中,各节点彼此关联,空间利用率高,插入删除效率高,随机访问不方便。
二、堆栈
1.基本特征:后进先出。

2.基本操作:压入(push),弹出(pop)

3.实现要点:初始空间,栈顶指针,判空判满。



代码实现:

// 顺序表堆栈
#include <iostream>
using namespace std;
// 堆栈
class Stack {
public:
  // 构造函数
  Stack (size_t size = 10) : m_data (new int[size]), m_top (0), m_size (size) {}
  // 析构函数
  ~Stack (void) {
    if (m_data) {
      delete m_data;
      m_data = NULL;
    }
  }
  // 压入
  void push (int data) {
    if (m_top >= m_size)
      throw OverFlow ();
    m_data[m_top++] = data;
  }
  // 弹出
  int pop (void) {
    if (! m_top)
      throw UnderFlow ();
    return m_data[--m_top];
  }
  // 空否
  bool empty (void) {
    return ! m_top;
  }
private:
  // 上溢异常
  class OverFlow : public exception {
  public:
    const char* what (void) const throw () {
      return "堆栈上溢!";
    }
  };
  // 下溢异常
  class UnderFlow : public exception {
  public:
    const char* what (void) const throw () {
      return "堆栈下溢!";
    }
  };
  int* m_data; // 数组
  size_t m_top; // 栈顶
  size_t m_size; // 容量
};
int main (void) {
  try {
    Stack stack;
    for (size_t i = 0; i < 10; i++)
      stack.push (i);
    //stack.push (10);
    while (! stack.empty ())
      cout << stack.pop () << endl;
    //stack.pop ();
  }
  catch (exception& ex) {
    cout << ex.what () << endl;
    return -1;
  }
  return 0;
}


// 链表堆栈
#include <iostream>
using namespace std;
// 堆栈
class Stack {
public:
  // 构造函数
  Stack (void) : m_top (NULL) {}
  // 析构函数
  ~Stack (void) {
    for (Node* next; m_top; m_top = next) {
      next = m_top -> m_next;
      delete m_top;
    }
  }
  // 压入
  void push (int data) {
    m_top = new Node (data, m_top);
  }
  // 弹出
  int pop (void) {
    if (! m_top)
      throw UnderFlow ();
    int data = m_top -> m_data;
    Node* next = m_top -> m_next;
    delete m_top;
    m_top = next;
    return data;
  }
  // 空否
  bool empty (void) {
    return ! m_top;
  }
private:
  // 下溢异常
  class UnderFlow : public exception {
  public:
    const char* what (void) const throw () {
      return "堆栈下溢!";
    }
  };
  // 节点
  class Node {
  public:
    Node (int data = 0, Node* next = NULL) : m_data (data), m_next (next) {}
    int m_data;
    Node* m_next;
  };
  Node* m_top; // 栈顶
};
int main (void) {
  try {
    Stack stack;
    for (size_t i = 0; i < 10; i++)
      stack.push (i);
    //stack.push (10);
    while (! stack.empty ())
      cout << stack.pop () << endl;
    //stack.pop ();
  }
  catch (exception& ex) {
    cout << ex.what () << endl;
    return -1;
  }
  return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值