链表本身天然就有一个递归的性质
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode removeElements(ListNode head, int val) {
while(head!=null && head.val == val){
ListNode delNode = head;
head = head.next;
delNode.next = null;
}
if(head == null)
{
return null;
}
ListNode prev = head;
while(prev.next!=null){
if(prev.next.val==val){
ListNode delNode = prev.next;
prev.next = delNode.next;
delNode.next = null;
}
else{
prev = prev.next;
}
}
return head;
}
}
虚拟头节点解法
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode removeElements(ListNode head, int val) {
ListNode dumyHead = new ListNode(-1);
dumyHead.next = head;
ListNode prev = dumyHead;
while(prev.next!=null){
if(prev.next.val==val){
// ListNode delNode = prev.next;
prev.next = prev.next.next;
// delNode.next = null;
}
else{
prev = prev.next;
}
}
return dumyHead.next;
}
}
本地调试这个算法
ListNode
//Definition for singly-linked list.
public class ListNode {
public int val;
public ListNode next;
public ListNode(int x) {
val = x;
}
// 链表节点的构造函数
// 使用arr为参数,创建一个链表,当前的ListNode为链表头结点
public ListNode(int[] arr){
if(arr == null || arr.length == 0)
throw new IllegalArgumentException("arr can not be empty");
this.val = arr[0];
ListNode cur = this;
for(int i = 1 ; i < arr.length ; i ++){
cur.next = new ListNode(arr[i]);
cur = cur.next;
}
}
// 以当前节点为头结点的链表信息字符串
@Override
public String toString(){
StringBuilder s = new StringBuilder();
ListNode cur = this;
while(cur != null){
s.append(cur.val + "->");
cur = cur.next;
}
s.append("NULL");
return s.toString();
}
}
main
public static void main(String[] args) {
int[] nums = {1, 2, 6, 3, 4, 5, 6};
ListNode head = new ListNode(nums);
System.out.println(head);
ListNode res = (new Solution3()).removeElements(head, 6);
System.out.println(res);
}
}
递归
数组求和
public class Sum{
public static int sum(int[] arr){
return sum(arr,0);
}
//计算arr[l...n)这个区间诶所有数字的和
private static int sum(int [] arr ,int l){
if(l == arr.length)
return 0;
return arr[l] + sum(arr,l+1);
}
}
链表的天然递归性
递归解决203删除指定元素
class Solution {
public ListNode removeElements(ListNode head, int val) {
if(head == null)
return null;
ListNode res = removeElements(head.next,val);
if(head.val == val)
return res;
else{
head.next = res;
return head;
}
}
}
递归函数的微观解读
模拟调用
6--->7--->8--->null
public ListNode removeElements(ListNode head , int val){
if(head == null)
return null;
head.next = removeElements(head.next,val);
return head.val == val ? head.next : head;
}