C++ 链表 基本操作

#include<iostream>
using namespace std;

struct node //节点名为node
{
    int data;
    node* next;
    node() :  data(0),next(nullptr) {}  //构造函数
    node(int x):data(x),next(nullptr){} // NULL容易引起二义性,nullptr更好一点
    node(int x, node* n) : data(x), next(n) {}
};



node* createlist() //创建长度为n的链表
{
    node* head = new node(); //创建空的头节点,此后一直认为头节点是空的
    node* p = head; //创建指针指向头节点
    int n = 0; //n为要输入的节点个数
    cout << "请输入要创建的列表长度" << endl;
    cin >> n;
    cout << "请输入节点数值" << endl;
    for (int i = 0; i < n; i++)//用for循环输入节点的数,建立链表
    {
        int x = 0;
        cin >> x;
        node* newnode = new node(x);
        head->next = newnode;
        head = head->next;

    }
    head = p; // 输入到此结束
    return head;

}

int length(node*h) //获取链表长度
{
    int count = 0;
    while (h->next!=nullptr)
    {
        h = h->next;
        count++;
    }
    return count;
}


void insert(node*h,int x, int y) //在元素前插入y
{
    node* newnode = new node(y);
    node* curr = h;

    while (curr->next)
    {
        if (curr->next->data == x)
        {
            newnode->next = curr->next;
            break;
        }
        curr = curr->next;
    }
    curr->next = newnode;
}

void append(node*h,int x) //在头指针为h的链表的结尾插入新节点,元素为x
{
    node* newp = new node(x);
    if (h->next == nullptr)
        h->next = newp;
    else
    {
        while (h->next != nullptr)
            h = h->next;
        h->next = newp;
    }
}

void remove_x(node* h, int x) //删掉第一个值为x的元素
{
    node* de = h ; // 暂存被删除节点,用于释放其占用的内存
    if (h == nullptr)  // 链表为空
        return;
    while (h->next->data != x)
        h = h->next;
    de = h->next;
    h->next = h->next->next;
    if(de!=nullptr)
        delete de;

}


void print(node* h) //打印链表,参数为某链表的头指针,操作不改变实参
{
    node* n = h->next;   // 因为带头节点,因此需要从head->next开始遍历链表
    if (n == nullptr)    //若是空链表,输出 NULL
        cout << "NULL" << endl;
    else
    {
        while (n != nullptr)
        {
            cout << n->data<<' ';
            n = n->next;
        }
        cout << endl;
    }
}

int main()
{
    node* head = createlist();

    insert(head, 4, 27);
    print(head);


}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值