[LeetCode]题解(python):092 Reverse Linked List II

题目来源


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->NULLm = 2 and n = 4,

return 1->4->3->2->5->NULL.

Note:
Given mn satisfy the following condition:
1 ≤ m ≤ n ≤ length of list.


题意分析


Input:一个链表

Output:翻转后的链表

Conditions:给定翻转的起始位置和终止位置,翻转链表


题目思路


关键是理清变换的思路,注意在链表的操作中,经常设置一个空的头节点。

代码思路如图(注意哪些在变化,至于旋转了,程序员你懂的)

[LeetCode]题解(python):092 Reverse Linked List II


AC代码(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
"""
if head == None or head.next == None:
return head
newHead = ListNode(0)
newHead.next = head
head1 = newHead
for i in range(m - 1):
head1 = head1.next
p = head1.next
print p.val
for i in range(n - m):
tmp = head1.next
head1.next = p.next
p.next = p.next.next
head1.next.next = tmp
print p.val, head1.val
return newHead.next
上一篇:JAVA基础知识总结:四


下一篇:python中使用kazoo连接zookeeper(一)