删除链表中等于给定值 val 的全部节点。数据结构
输入: 1->2->6->3->4->5->6, val = 6
输出: 1->2->3->4->5
遍历链表,找出每一个待删除节点的前一个节点。
特殊状况:第一个节点就是待删除节点时,要单独操做。
注意点:当输入为:[1,1]时,按上面的思路删除第一个节点,剩下的链表的头节点又是待删除节点。app
public ListNode removeElements(ListNode head, int val) { while(head != null && head.val == val){ ListNode pre = head; head = pre.next; pre.next = null; } if(head == null){ return null; } ListNode pre = head; while(pre.next!=null){ ListNode cur = pre.next; if(cur.val == val){ pre.next = cur.next; cur.next = null; }else{ pre = pre.next; } } return head; }
使用虚拟头结点(统一头节点和其余节点的操做)简化代码:ide
private class ListNode { int val; ListNode next; ListNode(int x) { val = x; } } public ListNode removeElements(ListNode head, int val) { ListNode dummyHead = new ListNode(-1); dummyHead.next = head; ListNode pre = dummyHead; while(pre.next!=null){ ListNode del = pre.next; if(del.val == val){ pre.next = del.next; del.next = null; }else{ pre = pre.next; } } return dummyHead.next; }
注意:这里返回时不能直接return head;函数
测试用例:测试
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(); } }
public ListNode removeElements(ListNode head, int val) { if(head == null){ return null; } head.next = removeElements(head.next, val); if(head.val == val){ return head.next; }else{ return head; } }
参考:《玩转数据结构》ui