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;
    }
    
  • 相关阅读:
    ssm框架中的struts我的配置问题
    ssm框架web.xml中filter配置问题
    partition-list
    entity.Student@150f3932, entity.Student@1a740c6b 没有实体中的数据
    UVA 11361 Investigating Div-Sum Property
    UVA 10883 Supermean
    Gym 101081K Pope's work
    UVA 1103 How Many O's?
    HOJ 1108
    HDU 5936 朋友
  • 原文地址:https://www.cnblogs.com/Jacob98/p/12465473.html
Copyright © 2011-2022 走看看