代码的鲁棒性---反转链表

博客围绕输入链表反转问题展开,给出两种思路。一是从头到尾遍历链表,用两个指针改变元素指向;二是使用递归,递归到链表尾端更新元素指向。还给出了Python实现代码。

题目描述:

输入一个链表,反转链表后,输出新链表的表头。

思路:
思路1:
从头到尾遍历链表,每到一个新元素时,定义两个指针preNode和nextNode,preNode指向当前元素的上一个元素,nextNode指向当前元素的下一个元素。改变当前元素的指向为preNode,并将preNode和nextNode均向右移动一位。
Python实现1:

// An highlighted block
def ReverseList(self, pHead):
    preNode = None
    while pHead:
        nextNode = pHead.next
        pHead.next = preNode
        preNode, pHead = pHead, nextNode
    return preNode

原文:https://blog.csdn.net/u010005281/article/details/79873244 

思路2:使用递归实现。不断递归到链表的尾端,更新尾端元素指向其上一个元素,并断开上一个元素的指向。

// An highlighted block
class Solution:
    # 返回ListNode
    def ReverseList(self, pHead):
        if not pHead or not pHead.next:
            return pHead
        
        nextNode = pHead.next
        newHead = self.ReverseList(nextNode)
        nextNode.next = pHead
        pHead.next = None
        return newHead
        # write code here

Python实现3:

// An highlighted block
class Solution:
    # 返回ListNode
    def ReverseList(self, pHead):
        # write code here
        if not pHead or not pHead.next:
            return pHead
        last = None
        
        while pHead:
            tmp = pHead.next
            pHead.next=last
            last=pHead
            pHead=tmp
        return last
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值