Leetcode92. Reverse Linked List II
反转链表的题没啥难的,就是多弄几个指针,别断链丢节点就行。
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode reverseBetween(ListNode head, int m, int n) {
if(head==null) return null;
ListNode dummy = new ListNode(-1);
dummy.next=head;
ListNode pre = dummy;
ListNode phead = head;
ListNode ptail = head.next;
for(int i=1;i<m;i++){
pre = pre.next;
phead = phead.next;
ptail = ptail.next;
}
for(int i=0;i<n-m;i++){
ListNode temp = ptail.next;
ptail.next = phead;
phead = ptail;
ptail = temp;
}
pre.next.next = ptail;
pre.next = phead;
return dummy.next;
}
}
Runtime: 0 ms, faster than 100.00% of Java online submissions for Reverse Linked List II.
Memory Usage: 35.8 MB, less than 92.53% of Java online submissions for Reverse Linked List II.