题解 | #链表内指定区间反转#
链表内指定区间反转
https://www.nowcoder.com/practice/b58434e200a648c589ca2063f1faf58c
package main // import "fmt" import . "nc_tools" /* * type ListNode struct{ * Val int * Next *ListNode * } */ /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param head ListNode类 * @param m int整型 * @param n int整型 * @return ListNode类 */ func reverseBetween(head *ListNode, m int, n int) *ListNode { // write code here var start, end *ListNode dummy := new(ListNode) dummy.Next = head start = dummy for i := 0; i < m-1; i++ { start = start.Next } end = start.Next for i := 0; i <= n-m; i++ { if end != nil { end = end.Next } } p := start.Next start.Next = end for i := 0; i <= n-m && p != nil; i++ { tmp := p p = p.Next tmp.Next = start.Next start.Next = tmp } return dummy.Next }