'''
反转从位置 m 到 n 的链表。请使用一趟扫描完成反转。
说明:
1 ≤ m ≤ n ≤ 链表长度。
示例:
输入: 1->2->3->4->5->NULL, m = 2, n = 4
输出: 1->4->3->2->5->NULL
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/reverse-linked-list-ii
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
'''
# Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
'''
算法1:迭代算法,使用了3个变量实现反转链表功能
执行用时 :36 ms, 在所有 python3 提交中击败了83.88%的用户
内存消耗 :12.7 MB, 在所有 python3 提交中击败了99.32%的用户
'''
def reverseBetween(self, head: ListNode, m: int, n: int) -> ListNode:
pre, k = head, 2
while pre and k < m:
pre = pre.next
k += 1
if pre is None or pre.next is None or m >= n:
return head
p, q = pre.next, pre.next.next
while q and k < n:
r = q.next #指向q的后继
q.next = p #修改q的next指针
p, q = q, r#p、q均后移一位
k += 1
if m == 1: #此时pre=head
pre.next.next = pre
pre.next = q
return p
else:
pre.next.next = q
pre.next = p
return head
'''
算法2:迭代算法,假设m和n的值都是合法的
执行用时 :36 ms, 在所有 python3 提交中击败了83.88%的用户
内存消耗 :12.7 MB, 在所有 python3 提交中击败了99.32%的用户
'''
def reverseBetween2(self, head: ListNode, m: int, n: int) -> ListNode:
pre, k = head, 2
while k < m:
pre = pre.next
k += 1
if pre is None or pre.next is None or m >= n:
return head
p, q = pre.next, pre.next.next
while k < n:
r = q.next #指向q的后继
q.next = p #修改q的next指针
p, q = q, r#p、q均后移一位
k += 1
if m == 1: #此时pre=head
pre.next.next = pre
pre.next = q
return p
else:
pre.next.next = q
pre.next = p
return head
'''
算法3:迭代算法,设置一个头结点,可以免去很多判断
执行用时 :20 ms, 在所有 python3 提交中击败了100.00%的用户
内存消耗 :12.8 MB, 在所有 python3 提交中击败了99.32%的用户
'''
def reverseBetween3(self, head: ListNode, m: int, n: int) -> ListNode:
h = ListNode(0)
h.next = head #设置一个头结点,可以免去很多判断
pre, k = h, 2
while k <= m:
pre = pre.next
k += 1
p, q = pre.next, pre.next.next
while k <= n:
r = q.next #指向q的后继
q.next = p #修改q的next指针
p, q = q, r#p、q均后移一位
k += 1
pre.next.next = q
pre.next = p
return h.next
a = [1, 2, 3, 4, 5, 6, 7, 8]
p = ha = ListNode(a[0])
for x in a[1:]:
p.next = ListNode(x)
p = p.next
p = ha
while p is not None:
print(p.val, end=' ')
p = p.next
print()
x = Solution()
m, n = 1, 8
hb = x.reverseBetween3(ha, m, n)
p = ha
while p is not None:
print(p.val, end=' ')
p = p.next
print()
p = hb
while p is not None:
print(p.val, end=' ')
p = p.next
print()