题解 | #合并两个排序的链表#

合并两个排序的链表

https://www.nowcoder.com/practice/d8b6b4358f774294a89de2a6ac4d9337

import java.util.*;
public class Solution {
    public ListNode Merge (ListNode pHead1, ListNode pHead2) {
        // write code here
        //思路:遍历两个链表,保存,排序,输出
        if (pHead1 == null) return pHead2;
        if (pHead2 == null)return pHead1;
        if (pHead1 == null & pHead2 == null) return null;

        ArrayList<Integer> new_list = new ArrayList<>();  //定义一个新的list
        //遍历两个链表,存入list
	  	while (pHead1 != null) {
            new_list.add(pHead1.val);
            pHead1 = pHead1.next;
        }
        while (pHead2 != null) {
            new_list.add(pHead2.val);
            pHead2 = pHead2.next;
        }
	  	//排序
        Collections.sort(new_list);
		//把list转换成链表
        ListNode newnode = new ListNode(new_list.get(0));
        ListNode dummyHead = new ListNode(-1);
        ListNode cur = dummyHead;
        for (int i = 0; i < new_list.size(); i++) {
            cur.next = new ListNode(new_list.get(i));
            cur = cur.next;
        }
        return dummyHead.next;

    }
}

第二种用递归

import java.util.*;
public class Solution {
    public ListNode Merge (ListNode pHead1, ListNode pHead2) {
        // write code here
       if(pHead1 == null || pHead2 == null){
		 return pHead1 1= null? pHead1:pHead2;
	   }
	  if(pHead1.val < pHead2.val){
	  	pHead1.next = Merge(pHead1.next, pHead2);
		return pHead1;
	  }else{
	  pHead2.next = Merge(pHead1, pHead2.next);
	  return pHead2;
	  }
    }
}
牛客HOT101 文章被收录于专栏

牛客HOT101

全部评论

相关推荐

09-17 10:53
四川大学 C++
loveTy:你这些技能对大厂没用,而且四川大学因为之前地铁那个事件上了不少民营企业的黑名单。 去试一试国企,他们的黑名单没民营那么狠
点赞 评论 收藏
分享
09-09 21:23
门头沟学院 Java
程序员牛肉:小牛肉来也! 主要就是没有实习经历。因为你的投递方向肯定是中小厂。在小厂中,很少会有公司愿意花钱培养你。因此会更加青睐有实习的同学。再加上你的学历比较差一点,所以找不到是正常的。 跟简历项目啥的已经没有大关系了,就是差一份实习。秋招和日常实习一起投递吧。
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务