zoukankan      html  css  js  c++  java
  • 剑指offer[15]——反转链表

    题目描述

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

    这道题目我有两种思路跟大家分享,一个是建立临时数组,再一个就是利用指针了。

    临时数组

    这种方法就比较简单了,就是遍历一遍链表,遍历完成之后再遍历临时数组,新建链表进行赋值,最后返回即可。

    /*function ListNode(x){
        this.val = x;
        this.next = null;
    }*/
    function ReverseList(pHead)
    {
        let temp = [];
        while(pHead){
            temp.unshift(pHead.val);
            pHead = pHead.next;
        }
        if(temp.length == 0){return pHead;}
        let head = new ListNode(temp[0]);
        let res = head;
        for(let i=1; i<temp.length; i++){
            head.next = new ListNode(temp[i]);
            head = head.next;
        }
        return res;
    }
    
    

    指针

    这种方法相对上一种方法来说算法思想就比较好。请看下面的示意图:

    其实大家仔细看这张图的话应该是可以看明白的,就是新建两个指针precur,主要变换的是cur,我们在操作的时候首先要把cur.next存储下面,因为我们接下来要改变cur.next指向,不存的话接下来就不能操作了。存储下来之后再令cur.next=pre,改变指针指向,遍历知道最后一个节点就可以了。

    /*function ListNode(x){
        this.val = x;
        this.next = null;
    }*/
    function ReverseList(pHead)
    {
        if(!pHead || !pHead.next){return pHead;}
        let cur = pHead.next;
        let pre = pHead;
        pre.next = null;
        while(cur){
            let temp = cur.next;
            cur.next = pre;
            pre = cur;
            cur = temp;
        }
        return pre;
    }
    
  • 相关阅读:
    关于素数的具体问题
    Scala Apply
    Scala内部类
    Scala 类和对象
    Scala Tuple类型
    Scala数组
    sql server 游标
    表变量和临时表详解
    子查询详解
    EXEC 和 SP_EXECUTESQL的区别
  • 原文地址:https://www.cnblogs.com/Jacob98/p/12465473.html
Copyright © 2011-2022 走看看