zoukankan      html  css  js  c++  java
  • 5-4 链表的天然递归结构性质

    整个链表=头结点+后面整个链表

     1 class Solution4 {
     2 
     3     public ListNode removeElements(ListNode head, int val) {
     4 
     5         if(head == null)   //头结点为空,也就是整个链表为空,
     6             return head;  //对于一个空链表,要删除值为val的节点,结果还是空
     7 
     8         ListNode res = removeElements(head.next, val);
     9         //考虑头结点
    10         if(head.val == val)
    11             return res;//删除head,res存的就是head后面的节点
    12         else{      //head不要删除,
    13             head.next = res;  //head后面的子链表删除val的得到的子链表衔接到head后
    14             return head;
    15         }
    16     }
    17 
    18     public static void main(String[] args) {
    19 
    20         int[] nums = {1, 2, 6, 3, 4, 5, 6}; //声明一个数组是int[]类型的
    21         ListNode head = new ListNode(nums);//调用ListNode方法,这里的head实际上是一个链表,由于构造函数public ListNode(int[] arr)
    22         System.out.println(head);//这里的head虽然是一个头节点,但是根据我们在ListNode中覆盖的toString()方法,将打印以head为头节点的整个链表对应的字符串
    23 
    24         ListNode res = (new Solution4()).removeElements(head, 6);
    25         System.out.println(res);
    26     }
    27 }
     1 public class ListNode {
     2 
     3     public int val;
     4     public ListNode next;
     5 
     6     public ListNode(int x) {
     7         val = x;
     8     }
     9 
    10     // 链表节点的构造函数
    11     // 使用arr为参数,创建一个链表,当前的ListNode为链表头结点
    12     public ListNode(int[] arr){
    13 
    14         if(arr == null || arr.length == 0)
    15             throw new IllegalArgumentException("arr can not be empty");
    16 
    17         this.val = arr[0];  // this.val对应arr中索引为0的元素
    18         //遍历整个数组,在这个过程中,我们一个一个的将数组中的每一个元素创建成新的ListNode,接在前一个节点上
    19         ListNode cur = this;
    20         for(int i = 1 ; i < arr.length ; i ++){
    21             cur.next = new ListNode(arr[i]);
    22             cur = cur.next;  //最后我们的这个this其实是:用for循环创建出来的链表相对应的头节点
    23         }
    24     }
    25 
    26     // 以当前节点为头结点的链表信息字符串
    27     @Override
    28     public String toString(){
    29 
    30         StringBuilder s = new StringBuilder();
    31         ListNode cur = this;   //cur为链表,包含多个节点
    32         while(cur != null){
    33             s.append(cur.val + "->"); //cur.val被轮询到的某个链表节点的值
    34             cur = cur.next;
    35         }
    36         s.append("NULL");
    37         return s.toString();
    38     }
    39 }

     

    带女朋友搬家新家条件不好,累到女朋友了,让女朋友受苦了,特此明志:每天学习,明年这个时候(20190812)让女朋友住上大房子,永远年轻,永远热泪盈眶,很多人都是这样,他们都把自己当成身在梦中一样,浑浑噩噩地过日子,只有痛苦或爱或危险可以让他们重新感到这个世界的真实。
  • 相关阅读:
    98.公共汽车
    100.选菜(动态规划)01背包
    102.愤怒的LJF
    96.老鼠的旅行(动态规划)
    95.(01背包)之小吃
    94.Txx考试
    93.数字三角形W(深搜)
    POJ 3352 Road Construction (边双连通分量)
    POJ 3114 Countries in War(强联通分量+Tarjan)
    POJ 3592 Instantaneous Transference(强联通分量 Tarjan)
  • 原文地址:https://www.cnblogs.com/make-big-money/p/10328417.html
Copyright © 2011-2022 走看看