栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

2021-11-12 NC 78: 反转链表

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

2021-11-12 NC 78: 反转链表

NC78: 反转链表
python代码

class ListNode:
    def __init__(self, x):
        self.val = x
        self.next = None

    def print_list(self):
        while self.next is not None:
            print(self.val)
            self = self.next
        print(self.val)

# 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可


# @param head ListNode类
# @return ListNode类
#
class Solution:
    def ReverseList(self , head: ListNode) -> ListNode:
        # write code here
        if head is None:
            rhead = head
        elif head.next is None:
            rhead = head
        else:
            p = head
            q = head.next
            n = q.next
            p.next = None
            while n is not None:
                q.next = p
                p = q
                q = n
                n = n.next
            q.next = p
            rhead = q
        return rhead

if __name__ == '__main__':
    head = ListNode(1)
    # head1 = ListNode(2)
    # head.next = head1
    # head2 = ListNode(3)
    # head1.next = head2
    ListNode.print_list(head)
    a = Solution()
    rhead = Solution.ReverseList(a, head)
    ListNode.print_list(rhead)


主要思路就是利用,三个游标依次向后移动,每次都是反转一个指针,但是要考虑到特殊的情况,链表为空,链表只有一个结点,链表没有结点,和正常链表的三种情况,并且在第三章情况,跳出while循环的时候,注意条件是n is none 不是n.next is None

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/468149.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号