剑指offer----翻转链表的python实现

循环遍历链表,将链表中的元素从表头依次取出指向新链表即可
三个变量,head是要维护的输出结果,orghead是定位变量,tempNode是用来赋值的中间变量

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

class Solution(object):
    def reverseList(self,head):
        if not head:
            return head
        orghead=head
        while orghead.next:
            temp=orghead.next
            orghead.next=orghead.next.next
            temp.next=head
            head=temp
        return head
if __name__=="__main__":
    head=ListNode(2)
    head.next=ListNode(3)
    head.next.next=ListNode(4)
    su=Solution()
    result=su.reverseList(head)
    print(result.val,result.next.val,result.next.next.val)

对于类似于C中的指针的用法,一直没怎么搞明白,这里可以这样简单理解,当orgHead = head时,这两个变量本身的地址不同,但是是指向相同的东西,指针可以简单理解为指向哪一个,不用理解为赋值。。。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值