C++中其實有stack的模板類。功能更為強大。 
自己寫一個棧能讓我們對棧這種數據結構更加熟悉。這個棧有一個不足之處就是里面存放的元素類型只能為int。
#include <iostream>using namespace std;class Stack{private:  struct Node  {    int data;    Node *next;  };  Node *head;  Node *p;  int length;public:  Stack()  {    head = NULL;    length = 0;  }  void push(int n)//入棧  {    Node *q = new Node;    q->data = n;    if (head == NULL)    {      q->next = head;      head = q;      p = q;    }    else    {      q->next = p;      p = q;    }    length ++;  }  int pop()//出棧并且將出棧的元素返回  {    if (length <= 0)    {      abort();    }    Node *q;    int data;    q = p;    data = p->data;    p = p->next;    delete(q);    length --;    return data;  }  int size()//返回元素個數  {    return length;  }  int top()//返回棧頂元素  {    return p->data;  }  bool isEmpty()//判斷棧是不是空的  {    if (length == 0)    {      return true;    }    else    {      return false;    }  }  void clear()//清空棧中的所有元素  {    if (length > 0)    {      pop();    }  }};int main(){  //以下為測試代碼  Stack s;  s.push(1);  s.push(2);  s.push(3);  while(!s.isEmpty())  {    cout<<s.pop()<<endl;  }  return 0;}對這段代碼稍加修改,這個棧就能存放其他類型的元素
#include <iostream>using namespace std;template<class T>class Stack{private:  struct Node  {    T data;    Node *next;  };  Node *head;  Node *p;  int length;public:  Stack()  {    head = NULL;    length = 0;  }  void push(T n)//入棧  {    Node *q = new Node;    q->data = n;    if (head == NULL)    {      q->next = head;      head = q;      p = q;    }    else    {      q->next = p;      p = q;    }    length ++;  }  T pop()//出棧并且將出棧的元素返回  {    if (length <= 0)    {      abort();    }    Node *q;    int data;    q = p;    data = p->data;    p = p->next;    delete(q);    length --;    return data;  }  int size()//返回元素個數  {    return length;  }  T top()//返回棧頂元素  {    return p->data;  }  bool isEmpty()//判斷棧是不是空的  {    if (length == 0)    {      return true;    }    else    {      return false;    }  }  void clear()//清空棧中的所有元素  {    while(length > 0)    {      pop();    }  }};int main(){  Stack<char> s;  s.push('a');  s.push('b');  s.push('c');  while(!s.isEmpty())  {    cout<<s.pop()<<endl;  }  return 0;}感謝閱讀,希望能幫助到大家,謝謝大家對本站的支持!
新聞熱點
疑難解答
圖片精選