题解 | #牛群分隔#
牛群分隔
https://www.nowcoder.com/practice/16d9dc3de2104fcaa52679ea796e638e
链表的拆分与合并。为了合并的方便,引入了伪头指针。
package main import "fmt" import . "nc_tools" /* * type ListNode struct{ * Val int * Next *ListNode * } */ func cow_partition( head *ListNode , x int ) *ListNode { if head == nil{ fmt.Println() return head } pHead1, pHead2 := &ListNode{Next: head}, &ListNode{} prev, curr, curr2 := pHead1, head, pHead2 for curr != nil{ if curr.Val < x{ prev.Next = curr.Next curr2.Next = curr curr = curr.Next curr2 = curr2.Next curr2.Next = nil }else{ prev, curr = curr, curr.Next } } curr2.Next = pHead1.Next return pHead2.Next }