LeetCode OJ算法题(六十四):Merge Two Sorted Lists

题目:

Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first two lists.

解法:

实际上就是归并排序的链表实现。

一趟合并中,不再需要重新创建一个数组来保存合并的结果,因为这里是链表实现,因此,用p指向已经合并好的链表的尾部,l1指向第一张链表下一个应该比较的节点,l2指向第二个链表的下一个应该比较的节点。

接下来需要分开讨论:

如果l1<l2(这里省略了取val的操作),且p指向的是l1,中的节点(用p.next 与 l1比较可知),那么直接p=p.next;

如果l1<l2,且p指向l2的前一个节点,那么需要把p的next指向l2,然后l2后移,p后移

当l2<l1时操作类似。

最后当某一个链表遍历完后,把另一链表剩下的部分连接上去即可

public class No64_MergeTwoSortedLists {
	public static class ListNode {
		int val;
		ListNode next;
		ListNode(int x) {
			val = x;
			next = null;
		}
	}
	public static void main(String[] args){
		ListNode n1 = new ListNode(1);
		ListNode n2 = new ListNode(7);
		ListNode n3 = new ListNode(8);
		ListNode n4 = new ListNode(2);
		ListNode n5 = new ListNode(4);
		ListNode n6 = new ListNode(6);
//		n1.next = n2;
//		n2.next = n3;
		n4.next = n5;
		n5.next = n6;
		ListNode head = mergeTwoLists(n1, n4);
		while(head != null){
			System.out.println(head.val+" ");
			head = head.next;
		}
			
	}
	public static ListNode mergeTwoLists(ListNode l1, ListNode l2) {
		if(l1 == null) return l2;
		if(l2 == null) return l1;
        ListNode head;
        if(l1.val < l2.val){
        	head = l1;
        	l1 = l1.next;
        }
        else{
        	head = l2;
        	l2 = l2.next;
        }
        ListNode p = head;
        while(l1 != null && l2 != null){
        	if(l1.val < l2.val){
        		if(p.next != l1) p.next = l1;
        		p = p.next;
    			l1 = l1.next;	
        	}
        	else{
        		if(p.next != l2) p.next = l2;
        		p = p.next;
        		l2 = l2.next;
        	}
        }
        if(l1 == null) p.next = l2;
        if(l2 == null) p.next = l1;
        return head;
    }
}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值