反转链表
反转整个链表
/** * Definition for singly-linked list. * type ListNode struct { * Val int * Next *ListNode * } */ func reverseList(head *ListNode) *ListNode { if head==nil||head.Next==nil{ return head } last:=reverseList(head.Next) head.Next.Next=head head.Next=nil return last }
反转链表前N个节点
//反转前n个节点 func reverseN(head *ListNode, n int) *ListNode{ if n==1{ end = head.Next return head } last := reverseN(head.Next,n-1) head.Next.Next=head head.Next=end return last }
反转链表在区间(left,right)之间的节点
/** * Definition for singly-linked list. * type ListNode struct { * Val int * Next *ListNode * } */ func reverseBetween(head *ListNode, left int, right int) *ListNode { if left == 1{ return reverseN(head, right) } head.Next = reverseBetween(head.Next,left-1,right-1) return head } var end *ListNode = nil //反转前n个节点 func reverseN(head *ListNode, n int) *ListNode{ if n==1{ end = head.Next return head } last := reverseN(head.Next,n-1) head.Next.Next=head head.Next=end return last }