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

    题目描述

    输入一个链表,反转链表后,输出链表的所有元素。


    方法1:
    利用循环:
    pre head next
    1→2→3

     1 /*
     2 public class ListNode {
     3     int val;
     4     ListNode next = null;
     5 
     6     ListNode(int val) {
     7         this.val = val;
     8     }
     9 }*/
    10 public class Solution {
    11     public ListNode ReverseList(ListNode head) {
    12         if(head==null||head.next==null) return head;
    13         ListNode pre = head;
    14         head = head.next;
    15        _*** pre***__***.next=null;***_
    16         while(head!=null){
    17             ListNode next= head.next;
    18             head.next=pre;
    19             pre = head;
    20             head = next;
    21         }
    22         return pre;
    23     }
    24 }

    递归版:


    抽象出来

    1→2->3

    R(2)表示2节点以后的都已经反转好了,而且返回的是反转后的头结点3
    1->2←3



    我们要做的就是 把 1——>2反转成1<——2
    1——————>2
    pre head

    pre.next = null;
    head.next = pre;

    需要注意把pre.next 置为null

     1 public class Solution {
     2     public ListNode ReverseList(ListNode head) {
     3         if(head==null||head.next==null) return head;
     4         ListNode pre = head;
     5         head = head.next;
     6         ListNode rhead= ReverseList(head);
     7         _***pre***__***.next = null;***_
     8         head.next = pre;  
     9         return  rhead;
    10     }
    11 }
  • 相关阅读:
    做题总结
    关于SQLSERVER中用SQL语句查询的一些个人理解
    关于SQLSERVER联合查询一点看法
    C#中怎样实现序列化和反序列化
    java内部类的使用
    C#抽象类
    匿名类
    Foreach能够循环的本质
    C#索引器
    深入了解接口的使用
  • 原文地址:https://www.cnblogs.com/zle1992/p/8029770.html
Copyright © 2011-2022 走看看