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

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

    第一种用了四个指针,没有下一个简单

    public class Solution {
        public ListNode ReverseList(ListNode head) {
            if (head == null || head.next == null) {
                return head;
            }
            ListNode cur = head;
            ListNode p = head.next;
    
    
            while (p != null) {
                ListNode q = p.next;
                p.next = cur;
                cur = p;
                p = q;
            }
            head.next = null;
            return cur;
        }
    }
    
    class ListNode {
        int val;
        ListNode next = null;
    
        ListNode(int val) {
            this.val = val;
        }
    }

    这个解发用了三个,比较好

    public class Solution {
        public ListNode ReverseList(ListNode head) {
            if (head == null || head.next == null) {
                return head;
            }
    
            ListNode cur = head.next;
            head.next = null;//第一个节点变成尾节点,指向null
    
    //        下面是大于1个节点的情况
            while (cur != null) {
    
                ListNode temp = cur.next;
                cur.next = head;
                head = cur;
                cur = temp;
            }
            return head;
        }
    }
    
    class ListNode {
        int val;
        ListNode next = null;
    
        ListNode(int val) {
            this.val = val;
        }
    }
  • 相关阅读:
    js 平坦化控制流
    js变量名混淆
    ERR_CERT_INVALID
    ERR_CERT_AUTHORITY_INVALID
    @babel/preset-env
    @babel/plugin-transform-runtime
    terminal
    @babel/plugin-proposal-class-properties
    Zotero
    随记 日后整理
  • 原文地址:https://www.cnblogs.com/chengpeng15/p/10042074.html
Copyright © 2011-2022 走看看