Reverse a linked list from position m to n. Do it in one-pass.
Note: 1 ≤ m ≤ n ≤ length of list.
Example:
Input: 1->2->3->4->5->NULL, m = 2, n = 4
Output: 1->4->3->2->5->NULL
这个题我用了四个指针记录位置:left和right分别是翻转链表的两边(外),也就是1和5
然后用p和q记录当前要操作的点和这个点的下一个点,也就是2,3
接着就按照常规思路:2.next=5;3.next=2;4.next=3,然后left.next=4就可以了
# 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
left = right = dummy
length=n-m+1
while m>1:
left = left.next
m -= 1
while n>-1:
right = right.next
n -= 1
p = left.next
while length>0:
q=p.next
p.next=right
right = p
p = q
length -= 1
left.next=right
return dummy.next

本文介绍了一种在单次遍历中实现链表从位置m到n的反转算法。通过使用四个指针,分别记录翻转区间的两侧节点及当前操作节点,实现了高效的一次性反转。示例输入为1->2->3->4->5->NULL,m=2,n=4,输出为1->4->3->2->5->NULL。

被折叠的 条评论
为什么被折叠?



