C++利用链表写一个简单的栈实例详解

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;}

感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!

一个人的天地是冷得连呼吸都会寂寞的颤栗,而麻烦,

C++利用链表写一个简单的栈实例详解

相关文章:

你感兴趣的文章:

标签云: