92 Reverse Linked List II
从m到n位,对于链表进行反转
Python
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def reverseBetween(self, head, m, n):
"""
:type head: ListNode
:type m: int
:type n: int
:rtype: ListNode
"""
dummy = ListNode(-1)
dummy.next = head
pre = dummy
for i in range(m-1):
pre = pre.next
cur = pre.next
for i in range(m, n):
t = cur.next
cur.next = t.next
t.next = pre.next
pre.next = t
return dummy.next
Java
/**
* 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) {
ListNode fakeHead = new ListNode(-1);
fakeHead.next = head;
ListNode prev = fakeHead;
for(int i = 0; i < m - 1; i ++){
prev = prev.next;
}
ListNode curr = prev.next;
for(int i = m; i < n; i ++){
ListNode t = curr.next;
curr.next = t.next;
t.next = prev.next;
prev.next = t;
}
return fakeHead.next;
}
}