一次遍历反转链表

给你单链表的头指针 head 和两个整数 left 和 right ,其中 left <= right 。请你反转从位置 left 到位置 right 的链表节点,返回 反转后的链表 。

示例 1:

输入:head = [1,2,3,4,5], left = 2, right = 4
输出:[1,4,3,2,5]
示例 2:

输入:head = [5], left = 1, right = 1
输出:[5]

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/reverse-linked-list-ii
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

func reverseBetween(head *ListNode, left int, right int) *ListNode {
	if head==nil {
		return nil
	}
	pre:=new(ListNode)
	var curr,next,ret *ListNode
	ret=pre
	pre.Next=head
	curr=head
	for i:=1;i<left;i++{
		pre=pre.Next
		curr=curr.Next
	}
	for i:=0;i<right-left;i++{
		next=curr.Next
		curr.Next=next.Next
		next.Next=pre.Next
		pre.Next=next
	}
	return ret.Next
}
posted @ 2021-11-21 10:34  博客是个啥?  阅读(37)  评论(0编辑  收藏  举报