怎么在C++中使用链表书写一个栈-创新互联

怎么在C++中使用链表书写一个栈?很多新手对此不是很清楚,为了帮助大家解决这个难题,下面小编将为大家详细讲解,有这方面需求的人可以来学习下,希望你能有所收获。

让客户满意是我们工作的目标,不断超越客户的期望值来自于我们对这个行业的热爱。我们立志把好的技术通过有效、简单的方式提供给客户,将通过不懈努力成为客户在信息化领域值得信任、有价值的长期合作伙伴,公司提供的服务项目有:申请域名、网页空间、营销软件、网站建设、宁阳网站维护、网站推广。

C++中其实有stack的模板类。功能更为强大。

自己写一个栈能让我们对栈这种数据结构更加熟悉。这个栈有一个不足之处就是里面存放的元素类型只能为int。

#include 
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<

对这段代码稍加修改,这个栈就能存放其他类型的元素

#include 
using namespace std;
templateclass 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 s;
  s.push('a');
  s.push('b');
  s.push('c');
  while(!s.isEmpty())
  {
    cout<

看完上述内容是否对您有帮助呢?如果还想对相关知识有进一步的了解或阅读更多相关文章,请关注创新互联网站建设公司行业资讯频道,感谢您对创新互联建站的支持。

另外有需要云服务器可以了解下创新互联建站www.cdcxhl.com,海内外云服务器15元起步,三天无理由+7*72小时售后在线,公司持有idc许可证,提供“云服务器、裸金属服务器、建站服务器、香港服务器、美国服务器、虚拟主机、免备案服务器”等云主机租用服务以及企业上云的综合解决方案,具有“安全稳定、简单易用、服务可用性高、性价比高”等特点与优势,专为企业上云打造定制,能够满足用户丰富、多元化的应用场景需求。


本文标题:怎么在C++中使用链表书写一个栈-创新互联
转载来于:http://myzitong.com/article/ddiiie.html