Title: Reverse Linked List II Source: leetcode.com
Reverse a linked list from position m to n. Do it in-place and in one-pass.
For example:
Given 1->2->3->4->5->NULL
, m = 2 and n = 4,
return 1->4->3->2->5->NULL
.
Note:
Given m, n satisfy the following condition:
1 ≤ m ≤ n ≤ length of list.
Python solution
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 |
''' https://leetcode.com/problems/reverse-linked-list-ii/ ''' # 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 """ if not head: return head if m == n: return head i = 1 temp = head last = None while i < m: last = temp temp = temp.next i += 1 tail = temp nxt = temp.next prev = None while i < n: temp.next = prev prev = temp temp = nxt nxt = nxt.next i += 1 temp.next = prev tail.next = nxt if m == 1: head = temp else: last.next = temp return head |