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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值