链表与递归----力扣203题
力扣算法203题--移除链表元素
public class ListNode { int val; ListNode next; ListNode() { } ListNode(int val) { this.val = val; } ListNode(int val, ListNode next) { this.val = val; this.next = next; } //链表节点的构造函数 //使用arr为参数,创建一个链表,当前的ListNode为链表头节点 public ListNode(int[] arr){ if(arr == null && arr.length == 0) throw new IllegalArgumentException("arr cannot be empty."); this.val = arr[0]; ListNode cur = this; for (int i = 0; i < arr.length; i++) { cur.next = new ListNode(arr[i]); cur = cur.next; } } //以当前节点为头节点的链表信息字符串 @Override public String toString(){ StringBuilder res = new StringBuilder(); ListNode cur = this; while (cur != null){ res.append(cur.val+"->"); cur = cur.next; } res.append("NULL"); return res.toString(); } }
解法一:
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode() {} * ListNode(int val) { this.val = val; } * ListNode(int val, ListNode next) { this.val = val; this.next = next; } * } */ public 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 head; 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; } public static void main(String[] args) { int[] nums = {1,2,3,6,4,5,6}; ListNode listNode = new ListNode(nums); System.out.println(listNode); ListNode res = (new Solution()).removeElements(listNode,6); System.out.println(res); } }
运行结果:
1->1->2->3->6->4->5->6->NULL 1->1->2->3->4->5->NULL Process finished with exit code 0
解法二:使用虚拟头节点
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode() {} * ListNode(int val) { this.val = val; } * ListNode(int val, ListNode next) { this.val = val; this.next = next; } * } */ //通过虚拟头节点解决问题 public class Solution2 { public ListNode removeElements(ListNode head, int val) { ListNode dummyHead = new ListNode(-1); dummyHead.next = head; ListNode prev = dummyHead; while (prev.next != null){ if(prev.next.val == val) prev.next = prev.next.next; else prev = prev.next; } return dummyHead.next; } }