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

    反转链表

    反转一个单链表,主要就是改变节点的next值,每次循环的存储next的值,防止后面指针丢失了
    示例:
    输入: 1->2->3->4->5->NULL
    输出: 5->4->3->2->1->NULL

    循环

    注意:pre的值就是翻转的链表

    /**
     * Definition for singly-linked list.
     * function ListNode(val) {
     *     this.val = val;
     *     this.next = null;
     * }
     */
    let reverseList = (head) => {
            if (!head) {
              return null;
            }
            let pre = null;
            cur = head;
            while (cur) {
              //保存next
              let next = cur.next;
              //替换next
              cur.next = pre;
              //设置pre的值
              pre = cur;
              //设置当前项的值
              cur = next;
            }
          return pre;
          };
    

    每次循环pre和cur的值

    次数 pre cur
    第一次 1->null 2->3->4->5->NULL
    第二次 2->1->null 3->4->5->NULL
    第三次 3->2->1->null 4->5->NULL
    第四次 4->3->2->1->null 5->NULL
    第五次 5->4->3->2->1->null NULL

    递归

    let reverseList = (head) => {
            if (!head) {
              return null;
            }
            let reverse = (pre, cur) => {
              if (cur) {
                // 保存 next 节点
                let next = cur.next;
                cur.next = pre;
                return reverse(cur, next);
              }
              return pre;
            };
            return reverse(null, head);
          };
    
  • 相关阅读:
    JDK的KeyTool和KeyStore等加密相关
    关于分布式事务的随笔[待续]
    Netty实例几则
    Disruptor快速入门
    Java获取系统环境信息
    JDK的BIO, NIO, AIO
    四种常用IO模型
    JDK的多线程与并发库
    递归转换为迭代的一种通用方式
    二叉树的java实现
  • 原文地址:https://www.cnblogs.com/heihei-haha/p/14827086.html
Copyright © 2011-2022 走看看