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

LeetCode||92. Reverse Linked List II

2018-01-24 11:05 369 查看
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(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(0)
dummy.next = head
cur = dummy
for i in range(1, m):
cur = cur.next

tail = cur.next
for i in range(m, n):
if tail is None:
break
tmp = tail.next
tail.next = tmp.next
tmp.next = cur.next
cur.next = tmp

return dummy.next
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  LeetCode python