【LeetCode】21.合并两个有序链表

本文详细解析了LeetCode上的一道经典题目——合并两个有序链表,并分享了作者初次尝试时的错误理解及正确解答过程。文章通过对比两种不同逻辑的代码实现,深入探讨了链表操作的细节与难点,特别是对链表节点的next属性进行判断和处理的技巧。

leetcode 题目描述:

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

示例:

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

理解题意,我第一次以为是 顺序遍历所有节点。所以给出的答案是:

package leetcode; // eclipse 可执行
//   输入:1->2->4, 1->3->4  
//   输出:1->1->2->3->4->4
public class MergeTwoLists_21 {
	public static void main(String[] args) {
		ListNode l1 = new ListNode(1);
		l1.next = new ListNode(2);
		l1.next.next = new ListNode(3);

		ListNode l2 = new ListNode(4);
		l2.next = new ListNode(5);
		l2.next.next = new ListNode(6);
		
		ListNode l3 = mergeTwoLists(l1,l2);
		while(l3.next != null){
			
			System.out.print(l3.val+"->");
			l3 = l3.next;
		}
		System.out.print(l3.val);
	}
	public static ListNode mergeTwoLists(ListNode l1, ListNode l2) {

		if(l1 == null || l2 == null){
			return null;
		}
		if(l1 == null){
			return l2;
		}
		if(l2 == null){
			return l1;
		}
		ListNode l3 = new ListNode(0);
		ListNode temp = l3;
		while(true){	
			if(l1 != null){
				System.out.println(l1.val);
				temp.next = l1;
				l1 = l1.next;
				temp = temp.next;
			}
			if(l2 != null){
				System.out.println(l2.val);
				temp.next = l2;
				l2 = l2.next;
				temp = temp.next;
			}
			if(l1 == null && l2 == null){
				break;
			}
		}
		return l3;
	}
}

为此 想了好久的逻辑,主要是 判断 next 的部分,发现这个东西 跟 for 的边界一样麻烦。哼。

 

后来,看了 评论区,发现 是大小排序:所以最终提交代码:

/**
 * 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 l3 = new ListNode(0);
		ListNode curr = l3;
		while(l1 != null && l2 != null){	
			if(l1.val < l2.val){	
				curr.next = l1;
				l1 = l1.next;
				curr = curr.next;
			}else{
				curr.next = l2;
				l2 = l2.next;
				curr = curr.next;
			}
		}
		if(l1 == null){
			curr.next = l2;
		}
		if(l2 == null){
			curr.next = l1;
		}
		return l3.next;
    }
}

评级结果:

 

接触链表让我对对象有了新的认识,真的是万物可对象。

而且 链表给我的感觉 跟 C语言的指针有相似之处。不再是单纯的对象的赋值。

 

 

0.0.

 

 

 

0.0.

 

 

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值