zoukankan      html  css  js  c++  java
  • Leecode no.206 反转链表

    package leecode;

    /**
    * 206. 反转链表
    * 给你单链表的头节点 head ,请你反转链表,并返回反转后的链表。
    *
    * @author Tang
    * @date 2021/11/5
    */
    public class ReverseList {


    /**
    * 方法二:递归
    *
    * @param head
    * @return
    */
    public ListNode reverseList(ListNode head) {
    if(head == null) {
    return null;
    }
    return recurrence(head, null);

    }

    /**
    *
    * @param node 当前要调整的节点
    * @param last 调整后的下一个节点
    * @return
    */
    private ListNode recurrence(ListNode node, ListNode last) {
    //调整前的下一个节点
    ListNode temp = node.next;

    node.next = last;
    if(temp != null) {

    last = node;
    node = temp;
    return recurrence(node, last);
    }
    return node;
    }


    /**
    * 方法一: 迭代
    *
    * @param head
    * @return
    */
    // public ListNode reverseList(ListNode head) {
    // if(head == null) {
    // return null;
    // }
    //
    // //作为调整后的head.next指针
    // ListNode last = null;
    // //作为调整前的head的next指针
    // ListNode temp = null;
    // while(head.next != null) {
    // temp = head.next;
    // head.next = last;
    //
    // last = head;
    // head = temp;
    // }
    // head.next = last;
    // return head;
    // }





    public static void main(String[] args) {
    ListNode l1 = new ListNode();
    l1.val = 1;
    ListNode l2 = new ListNode();
    l2.val = 2;
    ListNode l3 = new ListNode();
    l3.val = 3;
    l1.next = l2;
    l2.next = l3;


    new ReverseList().reverseList(l1);



    }

    }
  • 相关阅读:
    SAX解析XML笔记
    使用 Angular 2 来创建FlexGrid控件
    算法-快速排序(优雅版)
    使用泛型简化动态代理
    Java泛型概述
    POI-PPT官方文档
    Java 利用POI操作PPT
    Java8学习笔记(九)--日期/时间(Date Time)API指南
    Java8学习笔记(八)--方法引入的补充
    Android WebView加载本地html并实现Java与JS交互
  • 原文地址:https://www.cnblogs.com/ttaall/p/15512106.html
Copyright © 2011-2022 走看看