Leetcode 206.反转链表(迭代与递归)最全解析

一.题目

在这里插入图片描述

二.解题思路

2.1 普通思路

反转箭头指向即可

cur设置为第一个元素1,pre为cur前的元素设置为None

  1. 先用temp保存下来cur的下一个元素temp = cur.next
    在这里插入图片描述
  2. 再将cur的箭头(cur.next)指向pre:cur.next = pre
    在这里插入图片描述
  3. pre与cur都向后移
    在这里插入图片描述
  4. 循环下去即可

2.2 递归思路

建议跟下文的代码结合看
第一次执行代码到ListNode newHead = reverseList(head.next);进入到第二次recursive,执行到同样的位置又进入了第三次recursive,三次recursive对应图中的1,2,3.
第三次recursive继续往下执行代码head.next.next=head;head.next=null;(图中4所示),此时head=3,head.next=null,箭头改变指向后结束第三次recursive,回到第二次recursive中(图中5所示)。
在这里插入图片描述

三.代码解析

3.1 普通方法

    def reverseList(self, head: ListNode) -> ListNode:
        pre = None #保存当前遍历的结点的前一个结点
        cur = head #cur是当前遍历的结点
        while  cur: #开始便利,cur不为null为循环条件
            temp = cur.next #temp保存cur.next
            cur.next = pre  #反转,cur指向pre
            pre = cur  #pre与cur都向后移
            cur = temp
        return pre #返回pre,即为新的头结点

3.2 递归方法

public ListNode reverseList(ListNode head) {
		#/*如果传入的节点等于null则之间返回head说明只有一个,无需反转*/
		#/*如果传入节点的下一个节点为null,说明递归结束,开始进行返回节点*/
        if (head==null||head.next==null){
            return  head;
        }
        #/*进行递归循环,newHead保存的是最后一个节点的位置*/
        ListNode newHead = reverseList(head.next);
        head.next.next=head;
        head.next=null;
        return  newHead;
    }

3.3 总方法及输出

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

class Solution:
    # Function to initialize head
    def __init__(self):
        self.head = None

    def reverseList(self, head: ListNode) -> ListNode:
        pre = None #保存当前遍历的结点的前一个结点
        cur = head #cur是当前遍历的结点
        while  cur: #开始便利,cur不为null为循环条件
            temp = cur.next #temp保存cur.next
            cur.next = pre  #反转,cur指向pre
            pre = cur  #pre与cur都向后移
            cur = temp
        return pre #返回pre,即为新的头结点

    # Function to insert a new node at the beginning
    def push(self, new_data):
        new_node = ListNode(new_data)
        new_node.next = self.head
        self.head = new_node
 
    # Utility function to print the linked LinkedList
    def printList(self):
        temp = self.head
        while(temp):
            print(temp.val)
            temp = temp.next

llist = Solution()
llist.push(7)
llist.push(6)
llist.push(5)
llist.push(4)
llist.push(3)
llist.push(2)
llist.push(1)
 
print("Given linked list")
llist.printList()

llist.head = llist.reverseList(llist.head)
 
print("\nReversed Linked list")
llist.printList()        

Output:

在这里插入图片描述

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值