题解 | #链表的奇偶重排#
链表的奇偶重排
https://www.nowcoder.com/practice/02bf49ea45cd486daa031614f9bd6fc3
用了fast,cur1、cur2。fast负责走路,把fast、fast.Next分别发给cu1、cur2。挺别扭的,感觉没有经典思路好。
package main import . "nc_tools" /* * type ListNode struct{ * Val int * Next *ListNode * } */ /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param head ListNode类 * @return ListNode类 */ func oddEvenList(head *ListNode) *ListNode { // write code here if head == nil { return head } dummy1 := &ListNode{} dummy2 := &ListNode{} cur1 := dummy1 cur2 := dummy2 fast := head for fast != nil && fast.Next != nil { cur1.Next = fast cur1 = cur1.Next cur2.Next = fast.Next cur2 = cur2.Next fast = fast.Next.Next } cur2.Next = nil cur1.Next = nil if fast == nil { cur1.Next = dummy2.Next return dummy1.Next } else if fast.Next == nil { //注意当fast == nil且没有提前return时,fast.Next不存在会触发panic cur1.Next = fast cur1 = cur1.Next cur1.Next = dummy2.Next return dummy1.Next } return nil }