面试题24:反转链表

这道题感觉很难,还没有理解

几天后:

面试题24:反转链表

# -*- coding:utf-8 -*-
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None
class Solution:
    # 返回ListNode
    def ReverseList(self, pHead):
        # write code here
        # 1.将现有的头换成尾,尾部的next为空
        # 2.将从第二个node开始,循环将next指向前一个
        # 3.需要有一个指针一直指向还没有反转的链表的表头
        if pHead == None:
            return None
        if pHead.next == None:
            return pHead
        
        leftpointer = pHead
        midpointer = pHead.next
        rightpointer = midpointer.next
        leftpointer.next = None
        while rightpointer != None:
            midpointer.next = leftpointer
            leftpointer = midpointer
            midpointer = rightpointer
            rightpointer = rightpointer.next
        midpointer.next = leftpointer
        return midpointer

  

上一篇:翻转链表


下一篇:C++反转链表