[leetcode] 合并两个排序列表 Merge Two Sorted Lists 【Java】

2021-09-24 12:01:23 浏览数 (3)

合并两个已排序的链接列表并将其作为新列表返回。新列表应该通过拼接前两个列表的节点来完成。

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.

例子:

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

解析:

  1. 先判空,空的话放回另一个即可
  2. 都不空的情况下,把第二个连接到第一个后边去(注意记录最后链表的长度)
  3. 裁员冒泡排序即可

代码:

代码语言:javascript复制
/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
        ListNode newlist = l1;
    	int num = 0;
    	if ( l1 == null ) {
			return l2;
		}else if ( l2 == null ) {
			return l1;
		}
    	while ( newlist.next != null ) {
			newlist = newlist.next;
			num   ;
		}
    	while ( l2 != null ) {
			newlist.next = l2;
			l2 = l2.next;
			newlist = newlist.next;
			num   ;
		}
    	for (int i = 0; i < num; i  ) {
    		newlist = l1;
    		while( newlist.next != null ) {
    			if ( newlist.next.val < newlist.val ) {
					int box = newlist.val;
					newlist.val = newlist.next.val;
					newlist.next.val = box;
				}
    			newlist = newlist.next;
    		}
		}
		return l1;
    }
}

希望我的回答对您有帮助~~

0 人点赞