您的位置:首页 > 编程语言 > Python开发

[leetcode]Reverse Linked List II @ Python

2014-06-12 10:05 281 查看
原题地址:https://oj.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.

解题思路:翻转链表的题目。

代码:

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
# @param head, a ListNode
# @param m, an integer
# @param n, an integer
# @return a ListNode
def reverseBetween(self, head, m, n):
if head == None or head.next == None:
return head
dummy = ListNode(0); dummy.next = head
head1 = dummy
for i in range(m - 1):
head1 = head1.next
p = head1.next
for i in range(n - m):
tmp = head1.next
head1.next = p.next
p.next = p.next.next
head1.next.next = tmp
return dummy.next
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: