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

    ##题目描述 输入一个链表,反转链表后,输出新链表的表头。

    思路

    原地反转链表指针。
    时间复杂度O(n),空间复杂度O(1)。

    代码

    /*
    public class ListNode {
        int val;
        ListNode next = null;
    
        ListNode(int val) {
            this.val = val;
        }
    }*/
    public class Solution {
        public ListNode ReverseList(ListNode head) {
            if(head == null)    return null;
            ListNode pre = null;
            ListNode curr = head;
            ListNode next = head.next;
            while(next != null) {
                curr.next = pre;
                pre = curr;
                curr = next;
                next = next.next;
            }
            curr.next = pre;
            return curr;
        }
    }
    
    public class Solution {
        public ListNode ReverseList(ListNode head) {
            if(head == null)    return null;
            ListNode pre = null;
            ListNode p = null;
            while(head != null) {
                p = head;
                head = head.next;
                p.next = pre;
                pre = p;
            }
            return p;
        }
    }
    

    笔记

    当while循环开始时的初设如编码所示时,根据while循环中使用了next.next,循环条件必须判断next的存在,不然会指针出错。

  • 相关阅读:
    【09】绝不在构造和析构过程中调用virtual方法
    【08】别让异常逃离析构函数
    C++ 外部调用private方法
    【07】为多态基类声明virtual析构方法
    C++ 构造过程和析构过程
    理解C# Lazy<T>
    DG
    MongoDB
    sh.status()
    DG
  • 原文地址:https://www.cnblogs.com/ustca/p/12327030.html
Copyright © 2011-2022 走看看