插入一个单链表

#include <iostream>
using namespace std;

typedef struct Node
{
    int val;
    struct Node* next;
}*pNode,Node;


pNode insert(pNode head, int value)
{
    if(head == NULL)
    {
        return NULL;
    }
    pNode h = head;
    pNode n = head->next;
    
    pNode pv = (pNode)malloc(sizeof(Node));
    if(pv == NULL)
    {
        cout<<"insert() malloc fail"<<endl;
        return head;
    }
    else
    {
        pv->val = value;
        pv->next = NULL;
    }
    
    
    while((h!=NULL) && (n!=NULL))
    {
        if(h->val > value)
        {
            pv->next = h;
            return pv;
        }
        if((h->val <= value) && (n->val >= value))
        {
            pv->next = n;
            h->next = pv;
            return head;
        }
        h = h->next;
        n = n->next;
    }
    if(n == NULL)
    {
        h->next = pv;
    }
    return head;
}

pNode creatLink()
{
    pNode head,tail,q;
    int x;
    head=tail=NULL;
    scanf("%d",&x);
    while(x!=0)
    {
        q=(pNode)malloc(sizeof(Node));
        q->val=x;
        if(head==NULL)
            head=tail=q;
        else
        {
            tail->next=q;
            tail=q;
        }
        scanf("%d",&x);
    }
    if(tail!=NULL)tail->next=NULL;
    return head;
}

void display(pNode head)
{
    pNode p = head;
    while(p!=NULL)
    {
        cout<<p->val<<endl;
        p = p->next;
    }
}
int main()
{
    pNode head = NULL;
    head = creatLink();
    cout<<"before insert"<<endl;
    display(head);
    
    int value = 0;
    scanf("%d",&value);
    cout<<"insert:"<<value<<endl;
    head = insert(head,value);
    cout<<"after insert"<<endl;
    display(head);

    
    
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值