zoukankan      html  css  js  c++  java
  • 递归

    一、递归


    二、链表天然的递归性


    三、递归解决LeetCode中203号问题(删除链表中的节点)

    删除链表中等于给定值 val 的所有节点。

    示例:

    输入: 1->2->6->3->4->5->6, val = 6
    输出: 1->2->3->4->5

     1 class Solution4 {
     2 
     3     public ListNode removeElements(ListNode head, int val) {
     4 
     5         if(head == null)
     6             return head;
     7 
     8         ListNode res = removeElements(head.next, val);
     9         if(head.val == val)
    10             return res;
    11         else{
    12             head.next = res;
    13             return head;
    14         }
    15     }
    16 
    17     public static void main(String[] args) {
    18 
    19         int[] nums = {1, 2, 6, 3, 4, 5, 6};
    20         ListNode head = new ListNode(nums);
    21         System.out.println(head);
    22 
    23         ListNode res = (new Solution4()).removeElements(head, 6);
    24         System.out.println(res);
    25     }
    26 }
     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];
    18         ListNode cur = this;
    19         for(int i = 1 ; i < arr.length ; i ++){
    20             cur.next = new ListNode(arr[i]);
    21             cur = cur.next;
    22         }
    23     }
    24 
    25     // 以当前节点为头结点的链表信息字符串
    26     @Override
    27     public String toString(){
    28 
    29         StringBuilder s = new StringBuilder();
    30         ListNode cur = this;
    31         while(cur != null){
    32             s.append(cur.val + "->");
    33             cur = cur.next;
    34         }
    35         s.append("NULL");
    36         return s.toString();
    37     }
    38 }

     

    
    
    

    四、递归调用是有代价的 


    五、更多和链表相关的话题 

  • 相关阅读:
    正则表达式
    特殊符号作用
    sed
    scp
    EOF
    env
    JAVA进阶5
    JAVA进阶4
    JAVA进阶3
    JAVA进阶2
  • 原文地址:https://www.cnblogs.com/mingmingmomo/p/9290058.html
Copyright © 2011-2022 走看看