(自用)单链表插入 (C++)

本文介绍了使用C++编写的链表操作函数,包括创建新节点和在已排序链表中插入元素的示例,通过`create`和`Insert`函数展示了如何动态管理节点数据。
摘要由CSDN通过智能技术生成

#include<iostream>
using namespace std;
typedef int datatype;
struct NODE {
    datatype data;
    struct NODE* next;
};
typedef struct NODE* node;
node create(node list,datatype x)
{
    node t, newnode = new NODE;
    newnode->data = x;
    newnode->next = NULL;
    if (list == NULL) list = newnode;
    else
    {
        t = list;
        while (t->next != NULL)
        {
            t = t->next;
        }
        t->next = newnode;
    }
    return list;
}
node Insert(node list,datatype x)
{
    node newnode = new NODE;
    node p, q;
    p = list;
    q = list;
    newnode->data = x;
    newnode->next = NULL;
    if (p == NULL)
    {
        p = newnode;
        return p;
    }
    else if (p->data >= x)
    {
        newnode->next = p;
        return newnode;
    }
    else
    {
        while (p->next!=NULL&&x>=p->data)
        {
            q = p;
            p = p->next;
        }
        if (p->next == NULL) p->next = newnode;
        else
        {
            newnode->next = q->next;
            q->next = newnode;
        }
        return list;
    }
}
int main()
{
    int n, i, x, y;
    node t=NULL;
    cin >> n;
    for (i = 1; i <= n; i++)
    {
        cin >> x;
        t = create(t, x);
    }
    cin >> y;
    t = Insert(t, y);
    while (t)
    {
        cout << t->data << " ";
        t = t->next;
    }
    return 0;
}

  • 4
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值