zoukankan      html  css  js  c++  java
  • 单链表的合并(递归、非递归)

    例:已知两个单链表head1和head2各自有序升序排列,请把他们合并成一个连表并依然有序,并保留原来所有节点

    假设以下两个链表:
    链表1:1->3->5
    链表2:2->4->6
    (1)比较1和链表2的第一个节点数据,由于1<2,因此把结果链表头结点指向链表1中的第一个节点,即数据1所在的节点
    (2)对剩余的链表1(3->5)和链表2在调用本过程,比较得到结果链表的第二个节点,即2与3比较得到2,此时合并后的链表节点为1->2,这样
    递归知道两个链表的节点都被加到结果链表中。
    node *mergerecursive(node *head1,node *head2)
    {
    if(head1==NULL)
    {
    return head2;
    }
    if(head2==NULL)
    {
    return head1;
    }
    node *head=NULL;
    if(head->data<head2->data)
    {
    head=head1;
    head->next=mergerecursive(head1->next,head2);
    }
    else
    {
    head=head2;
    head->next=mergerecursive(head1,head2->next);
    }
    return head;

    }

     

      非递归方式合并: 例:已知两个单链表head1和head2各自有序升序排列,请把他们合并成一个连表并依然有序,并保留原来所有节点
    因为head1和head2是有序的,所以只需要把较短链表的各个元素有序的插入到较长的链表之中就可以了

    node *t_node(node *head,node *item)

    { node *p=head;

    node *q=NULL;//始终指向p之前的节点

    while(p->data<item->data&&p!=NULL)

    { q=p; p=p->next; }

    if(p=head)

    插入到原头结点之前

    { item->next=p;

    return item; }

    插入到p与q之间

    q->next=item;

    item->next=p

    ; return head;

    }

    合并单链表

    node merge(node *head1,node *head2)
    {
    node *head;//合并后的头指针
    node *p;
    node *nextp;//指向p之后
    if(head1==NULL)//一个链表为空返回另一个链表
    {
    return head2;
    }
    else if(head2==NULL)//一个链表为空返回另一个链表
    {
    return head1;
    }
    两个链表都不为空
    if(length(head1)>=length(head2))//length()函数测单链表的长度,函数的使用见我的博客
    {
    head=head1;
    p=head2;
    }
    else
    {
    head=head2;
    p=head1;
    }
    while(p!=NULL)
    {
    nextp=p->next;//
    head=insert_node(head ,p);
    p=nextp;//指向要插入的下一个节点
    }
    return head;
    }

  • 相关阅读:
    序列操作
    random模块
    windows系统杀掉explorer.exe进程后黑屏
    Apache + SVN: Could not open the requested SVN filesystem
    使用ps命令批量删除相关进程
    'pybot.bat'不是内部或外部命令,也不是可运行的程序
    安装wxpython的时候报错 “no installation of python 2.7 found in registy”
    wxPython 使用Dialog实现模态对话框
    Python os.system()出现乱码
    Git操作reset --hard失误
  • 原文地址:https://www.cnblogs.com/zhangaihua/p/u12388338.html
Copyright © 2011-2022 走看看