Merge two sorted linked lists

Problem Statement

This challenge is part of a tutorial track by MyCodeSchool

You’re given the pointer to the head nodes of two sorted linked lists. The data in both lists will be sorted in ascending order. Change the next pointers to obtain a single, merged linked list which also has data in ascending order. Either head pointer given may be null meaning that the corresponding list is empty.

Input Format 
You have to complete the Node* MergeLists(Node* headA, Node* headB) method which takes two arguments - the heads of the two sorted linked lists to merge. You should NOT read any input from stdin/console.

Output Format 
Change the next pointer of individual nodes so that nodes from both lists are merged into a single list. Then return the head of this merged list. Do NOT print anything to stdout/console.

Sample Input

1 -> 3 -> 5 -> 6 -> NULL
2 -> 4 -> 7 -> NULL

15 -> NULL
12 -> NULL

NULL 
1 -> 2 -> NULL

Sample Output

1 -> 2 -> 3 -> 4 -> 5 -> 6 -> 7
12 -> 15 -> NULL
1 -> 2 -> NULL

Explanation 

1. We merge elements in both list in sorted order and output.


/*
  Insert Node at the end of a linked list 
  head pointer input could be NULL as well for empty list
  Node is defined as 
  class Node {
     int data;
     Node next;
  }
*/

Node MergeLists(Node list1, Node list2) {
     // This is a "method-only" submission. 
     // You only need to complete this method 
    if(list1==null&&list2==null)
        return null;
    if(list1==null||list2==null)
        return list1==null?list2:list1;
    Node p=new Node();
    Node q=new Node();
    Node start=new Node();
    
    if(list1.data>list2.data){
           p=list1;
           list1=list2;
           list2=p;
    }
    start=list1;
    
    while(list2!=null){
        while(list1.next!=null&&list1.next.data<list2.data){
            list1=list1.next;
        }
        if(list1.next==null){
            list1.next=list2;
            break;
        }
        q=list2.next;
        list2.next=list1.next;
        list1.next=list2;
        
        list2=q;
        list1=list1.next;
    }
    return start;
}


  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值