合并两个有序链表(merge-two-sorted-lists)

题目一:合并两个有序链表(merge-two-sorted-lists)

将两个有序链表合并为一个新的有序链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。

示例:

输入:1->2->4, 1->3->4
输出:1->1->2->3->4->4

递归方式

class Solution {
    public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
        if (l1 == null) {
            return l2;
        }
        else if (l2 == null) {
            return l1;
        }
        else if (l1.val < l2.val) {
            l1.next = mergeTwoLists(l1.next, l2);
            return l1;
        }
        else {
            l2.next = mergeTwoLists(l1, l2.next);
            return l2;
        }

    }
}

迭代方式

    public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
        // maintain an unchanging reference to node ahead of the return node.
        // 在返回节点之前保持对节点的不变引用。
        ListNode prehead = new ListNode(-1);
        ListNode prev = prehead;
        while (l1 != null && l2 != null) {
            if (l1.val <= l2.val) {
                prev.next = l1;
                l1 = l1.next;
            } else {
                prev.next = l2;
                l2 = l2.next;
            }
            prev = prev.next;
        }
        // exactly one of l1 and l2 can be non-null at this point, so connect
        // the non-null list to the end of the merged list.
        // 此时,l1和l2中的一个可以是非空的,因此将非空列表连接到合并列表的末尾。
        prev.next = l1 == null ? l2 : l1;
        return prehead.next;
    }

题目二:合并K个排序链表(merge-k-sorted-lists)

Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.

Example:

Input:
[
  1->4->5,
  1->3->4,
  2->6
]
Output: 1->1->2->3->4->4->5->6

逐一合并两条链表(容易看懂)

说白了,就是用上面的方法

class Solution {
    public ListNode mergeKLists(ListNode[] lists) {
        ListNode res = null;
        for (ListNode list: lists) {
            res = mergeTwoLists(res, list);
        }
        return res;
    }
}

K 个指针分别指向 K 条链表

class Solution {
    public ListNode mergeKLists(ListNode[] lists) { 
        int k = lists.length;
        ListNode dummyHead = new ListNode(0);
        ListNode tail = dummyHead;
        while (true) {
            ListNode minNode = null;
            int minPointer = -1;
            for (int i = 0; i < k; i++) {
                if (lists[i] == null) {
                    continue;
                }
                if (minNode == null || lists[i].val < minNode.val) {
                    minNode = lists[i];
                    minPointer = i;
                }
            }
            if (minPointer == -1) {
                break;
            }
            tail.next = minNode;
            tail = tail.next;
            lists[minPointer] = lists[minPointer].next;
        }
        return dummyHead.next;
    }
}

测试代码

主方法

    public static void main(String[] args) {
    	ListNode node1 = ListNode.createListNode(new int[] {1,4,5});
    	ListNode node2 = ListNode.createListNode(new int[] {1,3,4});
    	ListNode node3 = ListNode.createListNode(new int[] {2,6});
    	ListNode[] lists = new ListNode[] {node1,node2,node3};
    	ListNode.printListNode(lists);
    	
    	ListNode.printListNode(new Solution().mergeKLists(lists));
	}

生成一个单链表

    public static ListNode createListNode(int[] arr){
    	ListNode node1 = new ListNode(-1);
    	ListNode curr = node1;
    	for (int i = 0; i < arr.length; i++) {
    		curr.next = new ListNode(arr[i]);
    		curr = curr.next;
		}
		return node1.next;
    }

ListNode节点类

public class ListNode {

	public int val;
	public ListNode next;
	public ListNode(int x){val = x;}
	
	/**
	 * 生成一个单链表
	 * @param arr 
	 * @return
	 */
    public static ListNode createListNode(int[] arr){
    	ListNode node1 = new ListNode(-1);
    	ListNode curr = node1;
    	for (int i = 0; i < arr.length; i++) {
    		curr.next = new ListNode(arr[i]);
    		curr = curr.next;
		}
		return node1.next;
    }
    
    
	@Override
	public String toString() {
		ListNode ss = this;
		String s = "";
		while (ss != null) {
			String sss = ss.next == null ? "" : "->";
			s = s + ss.val + sss;
			ss = ss.next;
		}
		return s;
	}
	
	/**
	 * 打印单链表
	 * @param ss
	 */
	public static void printListNode(ListNode ss) {
		StringBuffer bf = new StringBuffer();
		while (ss != null) {
			bf.append(ss.val).append("->");
			ss = ss.next;
		}
		String s = bf.toString();
		System.out.println(s.substring(0, s.length()-2));
	}
	
	/**
	 * 打印单链表
	 * @param ss
	 */
	public static void printListNode(ListNode[] sss) {
		System.out.println("---"+sss.toString());
		for (ListNode ss : sss) {
			if (ss == null) {
				System.out.println("[]");
			}
			StringBuffer bf = new StringBuffer();
			while (ss != null) {
				bf.append(ss.val).append("->");
				ss = ss.next;
			}
			String s = bf.toString();
			System.out.println(s.substring(0, s.length() - 2));
		}
		System.out.println("---"+sss.toString());
	}
}

参考资料

seew

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值