Merge Two Sorted Lists—LeetCode

时间:2022-06-01 21:46:06

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.

https://leetcode.com/problems/merge-two-sorted-lists/

题意就是合并两个有序的链表,说实话,这个题我一开始还真有点轻视,不就是merge sort里一步么,但是真写起来代码,发现有点眼高手低了。因为没加头节点,来回的在current和next上操作,这么做也不是不可以,就是一会儿就搞晕了,还有点麻烦,学数据结构的时候,谈到链表,首先要有个头节点,这里我自己创建一个头节点head,还有个工作指针ptr。遍历两个链表哪个值小就append到ptr后面,最后把不为空的append到ptr后面。如果都为空,那么返回也是空。

Talk is cheap。

    public ListNode mergeTwoLists(ListNode l1, ListNode l2) {

        ListNode head = new ListNode(0);
ListNode ptr = head;
while (l1 != null && l2 != null) {
if (l1.val < l2.val) {
ptr.next = l1;
l1 = l1.next;
} else {
ptr.next = l2;
l2 = l2.next;
}
ptr = ptr.next;
}
ptr.next = l1 == null ? l2 : l1;
return head.next;
}