链表的各种操作函数总结

逆序生成函数

适用于生成n个节点的逆序链表。

node* reverse_add(int n)
{
    node *p,*head;
    head=new node;
   head->next=NULL;
    while(n--){
        p=new node;
        cin>>p->data;
        p->next=head->next;
        head->next=p;
    }
    return(head);
}
顺序生成函数

适用于生成n个节点的顺序链表。

node * add_farward(  int n)
{
    node *head,*p,*tail;
    head=new node;
    tail=head;
    while(n--)
    {
        p=new node;
        cin>>p->data;
        //p->next=NULL;//实验结果 可有可无
        tail ->next=p;
        tail=p;
	 }
    return head;
}
打印链表

适用于打印单个链表

void view(node * head)
{
    node *p;
    p=head->next;
    while(p)
    {
       p->next!=NULL?cout<<p->data<<' ':cout<<p->data<<endl;
        p=p->next;
    }
}
增加节点函数

适用于对链表head增加一个p节点的data值

node* ad(node *head,int m)
{
    node *p;
   {
        p=new node;
        p->data=m;
        p->next=head->next;
        head->next=p;
    }
    return(head);
}
拆分函数

运用了全局变量

void split(node * head)
{
    node *p;
    p=head->next;
    node *q=new node;
    head1=new node;
    head2=new node;
    //head1->next=NULL;
    //head2->next=NULL;
   // pp=head2->next;
    while(p)
    {
        if(p->dt%2==0)
        {
            ad(head2,p->dt);
            num1++;
        }
        else
        {
            ad(head1,p->dt); 
            num2++;
        }
        p=p->next;
    }
   // return head2;
}
链表的归并

适用于按顺序(升序)归并两个有序链表

node * merge_(node * head1,node * head2)
{
    node *p1,*p2,*tail;
    p1=head1->next;
    p2=head2->next;
    tail=head1;
    free(head2);
    while(p1&&p2)
    {
        if(p1->data<p2->data)
        {
            tail->next=p1;
            tail=p1;
            p1=p1->next;
        }
        else
        {
            tail->next=p2;
            tail=p2;
            p2=p2->next;
        }
    }
    if(p1)
        tail->next=p1;
    else
        tail->next=p2;
    return head1;
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值