46 lines
1.0 KiB
Java
46 lines
1.0 KiB
Java
/*
|
|
* @lc app=leetcode id=92 lang=java
|
|
*
|
|
* [92] Reverse Linked List II
|
|
*/
|
|
|
|
// @lc code=start
|
|
/**
|
|
* 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 {
|
|
/**
|
|
* 链表逆序:头插法
|
|
* @param head
|
|
* @param left
|
|
* @param right
|
|
* @return
|
|
*/
|
|
public ListNode reverseBetween(ListNode head, int left, int right) {
|
|
ListNode dummy = new ListNode(0);
|
|
dummy.next = head;
|
|
ListNode prev = dummy;
|
|
for(int i = 0; i< left-1; i++) {
|
|
prev = prev.next;
|
|
}
|
|
ListNode cur = prev.next;
|
|
ListNode tail = cur, tmp;
|
|
for(int i = 0; i < right-left; i++) {
|
|
cur = tail.next;
|
|
tail.next = cur.next;
|
|
cur.next = prev.next;
|
|
prev.next = cur;
|
|
}
|
|
return dummy.next;
|
|
}
|
|
}
|
|
// @lc code=end
|
|
|