ZBLOG

1. 已知链表结构为:typedef struct Node{int data; struct Node *next;}Node;编写函数实现:合并两个有序链表,使之仍然有序。函数原型为:Node * merge(Node*h1,Node*h2);

Node * merge(Node*h1, Node*h2){

if(h1 == NULL) return h2; // 如果一个链表为空,则返回另一个链表
if(h2 == NULL) return h1;

Node* head = NULL; // 合并后的头结点
Node* tail = NULL; // 合并后的尾结点

if(h1->data < h2->data){  // 确定合并后的头结点
    head = h1;
    h1 = h1->next;
}else{
    head = h2;
    h2 = h2->next;
}

tail = head; // 将tail指向head

while(h1 && h2){   // 遍历两个链表,找到最小值节点,并加入新链表中
    if(h1->data < h2->data){
        tail->next = h1;
        tail = tail->next;
        h1 = h1->next;
    }else{
        tail->next = h2;
        tail=tail->next;
        h2=h2->next;
    }
}

if(h1 != NULL)   // 将未遍历完的剩余节点加入新链表中
    tail -> next=h1;

if(h2 !=NULL)
    tail -> next=h2;

return head;  // 返回合并后的头结点

}

本站部分文章来源于网络,版权归原作者所有,如有侵权请联系站长删除。
转载请注明出处:https://golang.0voice.com/?id=5773

分享:
扫描分享到社交APP
上一篇
下一篇
发表列表
游客 游客
此处应有掌声~
评论列表

还没有评论,快来说点什么吧~

联系我们

在线咨询: 点击这里给我发消息

微信号:3007537140

上班时间: 10:30-22:30

关注我们
x

注册

已经有帐号?