题目如下:

【leetcode】92:反转链表 II_while循环

 

 本题目的精华在于不要用一个for循环遍历整个linked list,而是使用两个for或者三个for对同一个linked list从前到后进行遍历,同样也只遍历O(the number of nodes)=O(N)次,我尝试过仅使用一个while循环来写,虽然也是o(n),但是在穿针引线,也就是处理表头和表尾,left左边的元素和right右边的元素和中间反转链表需要进行分类讨论,比较麻烦,因为有可能遇到反转链表的左边或者没有元素的情况,因此使用两个while分别遍历整个linked list:

代码如下:

# Definition for singly-linked list.
# class ListNode(object):
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution(object):
    def reverseBetween(self, head, left, right):
        count = 1
        dummy = ListNode(0)
        dummy.next = head
        pre = dummy
        while pre.next and count < left:
            pre = pre.next
            count += 1
        cur = pre.next
        tail = cur
        while cur and count <= right:
            nxt = cur.next
            cur.next = pre.next
            pre.next = cur
            tail.next = nxt
            cur = nxt
            count += 1
        return dummy.next

得解!