zoukankan      html  css  js  c++  java
  • #206 反转链表

    题目:

     解题过程:

    思路一:迭代

        迭代需要三个指针,pre,cur,nxt,分别按顺序指向三个节点
        三个指针的初始化:pre指向空节点,cur指向头结点head,nxt指向head.next
        因为head.next可能不存在,nxt在循环中定义,这样如果head为空就不会进入循环
        迭代过程
            nxt指向cur.next
            cur.next指向pre
            pre移动到cur位置
            cur移动到nxt位置
        当cur为空时,返回pre

    链接:https://leetcode-cn.com/problems/reverse-linked-list/solution/shi-pin-tu-jie-206-fan-zhuan-lian-biao-d-zvli/

    代码:

    # Definition for singly-linked list.
    # class ListNode:
    #     def __init__(self, val=0, next=None):
    #         self.val = val
    #         self.next = next
    class Solution:
        def reverseList(self, head: ListNode) -> ListNode:
            pre =None
            cur=head
            while cur:
                nex = cur.next
                cur.next = pre
                pre = cur
                cur = nex
            return pre
  • 相关阅读:
    限制泛型可用类型
    泛型的常规用法(声明两个类型)
    一个类似于金字塔的图形
    Fibonacci数
    快来秒杀我
    奇偶数分离
    Background
    Financial Management
    HangOver
    Binary String Matching
  • 原文地址:https://www.cnblogs.com/wangyufeiaichiyu/p/14790918.html
Copyright © 2011-2022 走看看