JZ16 合并两个排序的链表
题目描述
输入两个单调递增的链表,输出两个链表合成后的链表,当然我们需要合成后的链表满足单调不减规则。
思路: 归并算法的思路,注意首先判断两个链表节点都不为空,判断大小while循环之后,要看哪个链表节点不为空,使用哨兵节点的方法处理头节点。
func Merge( pHead1 *ListNode , pHead2 *ListNode ) *ListNode { // write code here if pHead1 == nil && pHead2 == nil { return nil } if pHead1 == nil { return pHead2 } if pHead2 == nil { return pHead1 } dummyNode := &ListNode{Val: -1} head := dummyNode for pHead1 != nil && pHead2 != nil { if pHead1.Val < pHead2.Val { head.Next = pHead1 pHead1 = pHead1.Next } else { head.Next = pHead2 pHead2 = pHead2.Next } head = head.Next } if pHead1 != nil { head.Next = pHead1 } if pHead2 != nil { head.Next = pHead2 } return dummyNode.Next }