您的位置:首页 > 理论基础 > 数据结构算法

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

2014-04-17 10:50 429 查看
堆栈

一、基础数据结构

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;

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐