Leetcode - Reverse Linked List II
https://leetcode.com/problems/reverse-linked-list-ii/
Reverse a linked list from position m to n. Do it in one-pass.
Note: 1 ≤ m ≤ n ≤ length of list.
Example:
Input: 1->2->3->4->5->NULL, m = 2, n = 4 Output: 1->4->3->2->5->NULL
/** * Definition for singly-linked list. * type ListNode struct { * Val int * Next *ListNode * } */ func reverseBetween(head *ListNode, m int, n int) *ListNode { if m == n { return head } count := 1 node := head var head1 *ListNode for node != nil && count != m { count++ head1 = node node = node.Next } if node == nil { return head } tail1 := node var prev2 *ListNode for node != nil { count++ tmp := node.Next node.Next = prev2 prev2 = node node = tmp if count == n { tmp := node.Next node.Next = prev2 prev2 = node node = tmp break } } tail1.Next = node if head1 != nil { head1.Next = prev2 } else { return prev2 } return head }