zoukankan      html  css  js  c++  java
  • 剑指15.反转链表

    题目描述

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

    思路

    为了反转一个链表,需要调整链表中指针的方向。当调整节点 i 的指针指向时,需要知道节点 i 本身,还需要知道 i 的前一个节点 h,因为我们需要把节点 i 的指针指向节点 h 。同时,我们还需要提前保存 i 原来的下一个节点 j ,以防止链表断开。因此,需要3个指针,分别指向当前遍历到的节点,它的前一个节点以及后一个节点。
     

    代码实现

    /*
    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 || head.next == null)
                return head;
            ListNode pre = null;
            ListNode current = head;
            ListNode next = null;
            while(current != null){
                next = current.next;
                current.next = pre;
                pre = current;
                current = next;
            }
            return pre;
        }
    }
    // 第二种写法
    public class Solution {
        public ListNode ReverseList(ListNode head) {
            if(head == null || head.next == null)
                return head;
            ListNode pre = null;//注意要考虑到第一个节点,让它指向null
            ListNode next = null;
            while(head != null){
                next = head.next; //先记录一下当前节点的下一个节点,以防断开找不到下一个节点
                head.next = pre;
                pre = head;
                head = next;
            }
            return pre;
        }
    }
     
  • 相关阅读:
    DELPHI 各版本下载
    一个好的网站,学习前端
    没那么难,谈CSS的设计模式
    一个前端的自我修养
    如何学习Javascript
    jQuery WeUI V0.4.2 发布
    微信官方开源UI库-WeUI
    js与php传递参数
    ?js调用PHP里的变量,怎么弄?
    Liferay7 BPM门户开发之23: 了解内置工作流(Kaleo Workflow)
  • 原文地址:https://www.cnblogs.com/HuangYJ/p/13463106.html
Copyright © 2011-2022 走看看