赞
踩
给你单链表的头指针 head 和两个整数 left 和 right ,其中 left <= right 。请你反转从位置 left 到位置 right 的链表节点,返回 反转后的链表 。
92. 反转链表 II
left--right
位置链表反转。left
前面和right
后面断开,以left
位置为头结点进行反转left
前驱的next
应该指向right
位置的结点,left
位置的结点的next
应该是原来right
位置结点的后继。left
的前驱,left位置结点
,right位置结点
以及right
位置的后继结点。public ListNode reverseBetween(int left, int right) { if (head == null || head.next == null) { return head; } else { ListNode newHead = new ListNode(-1);//创建傀儡结点 newHead.next = head; //1.找到left的 前驱pre //从newHead 走 left-1 步 ListNode pre = newHead; for (int i = 0; i < left - 1; i++) { pre = pre.next; } //2.找到 right 结点 //再从pre 走 right-left+1 步 ListNode rightNode = pre; for (int i = 0; i < (right - left + 1); i++) { rightNode = rightNode.next; } //3.截取left--right链表 ListNode leftNode = pre.next;//left结点 ListNode suc = rightNode.next;//right的后继 //4.将 left之前 right之后 截断 pre.next = null; rightNode.next = null; //5.反转left--right reverseLinkedList(leftNode); //6.将链表连接起来 pre.next = rightNode; leftNode.next = suc; return newHead.next; } } public void reverseLinkedList(ListNode leftNode) { ListNode pre = null; ListNode cur = leftNode; while (cur != null) { ListNode curNext = cur.next; cur.next = pre; pre = cur; cur = curNext; } }
测试:
public static void main(String[] args) {
MyLinkedList myLinkedList = new MyLinkedList();
myLinkedList.addlast(1);
myLinkedList.addlast(2);
myLinkedList.addlast(3);
myLinkedList.addlast(4);
myLinkedList.addlast(5);
myLinkedList.display();
System.out.println("===============");
ListNode ret=myLinkedList.reverseBetween(2,4);
myLinkedList.display(ret);
}
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。