题目来源
https://leetcode.com/problems/reverse-linked-list-ii/
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.
题意分析
Input:一个链表
Output:翻转后的链表
Conditions:给定翻转的起始位置和终止位置,翻转链表
题目思路
关键是理清变换的思路,注意在链表的操作中,经常设置一个空的头节点。
代码思路如图(注意哪些在变化,至于旋转了,程序员你懂的)
AC代码(Python)
1 # Definition for singly-linked list. 2 # class ListNode(object): 3 # def __init__(self, x): 4 # self.val = x 5 # self.next = None 6 7 class Solution(object): 8 def reverseBetween(self, head, m, n): 9 """ 10 :type head: ListNode 11 :type m: int 12 :type n: int 13 :rtype: ListNode 14 """ 15 if head == None or head.next == None: 16 return head 17 newHead = ListNode(0) 18 newHead.next = head 19 head1 = newHead 20 for i in range(m - 1): 21 head1 = head1.next 22 p = head1.next 23 print p.val 24 for i in range(n - m): 25 tmp = head1.next 26 head1.next = p.next 27 p.next = p.next.next 28 head1.next.next = tmp 29 print p.val, head1.val 30 return newHead.next 31 32