题解 | #合并两个排序的链表#
合并两个排序的链表
https://www.nowcoder.com/practice/d8b6b4358f774294a89de2a6ac4d9337
package main import . "nc_tools" /* * type ListNode struct{ * Val int * Next *ListNode * } */ /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param pHead1 ListNode类 * @param pHead2 ListNode类 * @return ListNode类 */ //双指针方;把列表L2->合并到L1当中; L1多一个dummy Head, 保证是L2往L1迁移; //L1,L2的头分别指向最小的 //L1.Val < L2.Val && L1.Next.Val -> <= L2.Val {-> 移动 L1; -> 插入L2的val值; L2移动}; 直到有一方为空 func Merge(pHead1 *ListNode, pHead2 *ListNode) *ListNode { // write code here if pHead1 == nil { return pHead2 } if pHead2 == nil { return pHead1 } dummy := &ListNode{Val: -10000, Next: pHead1} h1 := dummy h2 := pHead2 for h1.Next != nil && h2 != nil { temp := h1.Next if temp.Val <= h2.Val { h1 = temp continue } temp2 := h2.Next h2.Next = temp h1.Next = h2 h2 = temp2 } if h1.Next == nil { h1.Next = h2 } return dummy.Next }#学习笔记#