链表的C++实现 (使用类实现

参考用书《数据结构》(秦锋,汤亚玲主编)
贴下代码:

#include <iostream>
#include <string>
using namespace std;
class Node{
   
public:
    string data;
    Node * next;
    Node()
    {
   
        next = NULL;
    }
};
class Link{
   
public :
    Node *head;//头指针
    Link()//构造函数
    {
   
        head = NULL;
    }
    ~Link(){
   //析构函数
        DeleteAll();
    }
    void Initiate(); //初始化
    void DeleteAll(); //删除所有节点
    void HeadCreate(int n);//头插法建表
    void TrailCreate(int n);//尾插法建表
    void HeadCreateWithHead(int n);//建立带表头的链表(从头)
    void TrailCreateWithTrail(int n);//建立带表头的链表(从尾)
    int Length(); //链表长度
    Node *Locatex(string data); //查找值为x的数据元素
    Node *Locatei(int i ); //取第i个元素值
    bool Insert(string data, int i);//在链表第i个元素之前插入x
    bool Deleted(int i); //删除链表中第i个结点
    void Print(); //打印链表
    string Get(int i); //读取第i个位置上的元素值
    void reverse(Link &H); //单链表的倒置
    void merge(Link &A,Link &B,Link &C)
    {
   
        Node *p, *q, *s;
        p=A.head->next; q=B.head->next; //p、q分别指向两个链表的第一个元素
        C.head->next=NULL;//初始化
        while((p!=NULL)&&(q!=NULL))
        {
   
            if(p->data<=q->data)
            {
   
                s=p;
              
  • 2
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是使用链表实现堆栈的C++代码: ```c++ #include <iostream> using namespace std; class Node { public: int data; Node* next; }; class Stack { private: Node* top; public: Stack() { top = nullptr; } void push(int val) { Node* newNode = new Node(); newNode->data = val; newNode->next = top; top = newNode; } bool isEmpty() { return top == nullptr; } int peek() { if (!isEmpty()) { return top->data; } else { cout << "Stack is empty!" << endl; return -1; } } void pop() { if (!isEmpty()) { Node* temp = top; top = top->next; delete temp; } else { cout << "Stack is empty!" << endl; } } }; int main() { Stack s; s.push(5); s.push(10); s.push(15); cout << s.peek() << endl; s.pop(); cout << s.peek() << endl; s.pop(); cout << s.peek() << endl; s.pop(); cout << s.peek() << endl; return 0; } ``` 在这个代码中,我们定义了两个:`Node`和`Stack`。`Node`表示堆栈中的一个节点,`Stack`表示堆栈本身。在`Stack`中,我们使用链表实现堆栈。具体地,`top`指针指向堆栈的顶部。当我们向堆栈中添加一个元素时,我们创建一个新的节点,将其指向当前的`top`节点,然后将`top`指针指向新的节点。当我们从堆栈中删除一个元素时,我们删除顶部节点,并将`top`指针指向下一个节点。 在`main`函数中,我们创建了一个堆栈对象`s`,并向其中添加了三个元素。然后,我们使用`peek`函数查看堆栈的顶部元素,并使用`pop`函数删除堆栈的顶部元素。最后,我们使用`peek`函数再次查看堆栈的顶部元素。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值