题解 | #合并两个排序的链表#
合并两个排序的链表
https://www.nowcoder.com/practice/d8b6b4358f774294a89de2a6ac4d9337
import java.util.*; /* * public class ListNode { * int val; * ListNode next = null; * public ListNode(int val) { * this.val = val; * } * } */ public class Solution { /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param pHead1 ListNode类 * @param pHead2 ListNode类 * @return ListNode类 */ public ListNode Merge (ListNode pHead1, ListNode pHead2) { // write code here if (pHead1 == null) { return pHead1; } ListNode cur = new ListNode(0); ListNode head = cur; while (pHead1 != null && pHead2 != null) { if (pHead1.val < pHead2.val) { cur.val = pHead1.val; pHead1 = pHead1.next; } else { cur.val = pHead2.val; pHead2 = pHead2.next; } cur.next = new ListNode(0); cur = cur.next; } while (pHead1 != null) { cur.val = pHead1.val; pHead1 = pHead1.next; if (pHead1 != null) { cur.next = new ListNode(0); cur = cur.next; } else { break; } } while (pHead2 != null) { cur.val = pHead2.val; pHead2 = pHead2.next; if (pHead2 != null) { cur.next = new ListNode(0); cur = cur.next; } else { break; } } return head; } }
双指针法,考虑到两个链表长度是一致的,一个为0则另一个也为0,边界处理返回哪个链表都行。后面主要考虑三种情况,两个链表都遍历完成、pHead1遍历完pHead2没遍历完、pHead2遍历完pHead1没遍历完。后续用比较简单的思路处理一下。
其实关于这些有序数据结构合并,基本就是三种思路:先合并再排序、双指针、逆双指针。本人水平有限,就先用双指针解题。