赞
踩
给你单链表的头指针 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]
反转链表记得用伪结点
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode() {} * ListNode(int val) { this.val = val; } * ListNode(int val, ListNode next) { this.val = val; this.next = next; } * } */ class Solution { public ListNode reverseBetween(ListNode head, int left, int right) { ListNode dummy = new ListNode(-1,head); // 翻转链表 ListNode pre_first = dummy; ListNode pre_second = dummy; ListNode cur_first = dummy; ListNode cur_second = dummy; for(int i=1;i<left&&pre_first!=null;i++){ pre_first = pre_first.next; } cur_first = pre_first.next; for(int i=1;i<=right&&cur_second!=null;i++){ cur_second = cur_second.next; } pre_second = cur_second.next; // 翻转 ListNode newHead = reverse(cur_first,pre_second); // 连接上 pre_first.next = newHead; cur_first.next = pre_second; return dummy.next; } public ListNode reverse(ListNode head,ListNode tail){ ListNode pre = null; ListNode next = null; while(head!=tail){ next = head.next; head.next = pre; pre = head; head = next; } return pre; } }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。