乐趣区

LeetCode【203】:移除链表元素

题目描述
删除链表中等于给定值 val 的所有节点。
示例
输入: 1->2->6->3->4->5->6, val = 6 输出: 1->2->3->4->5
非递归解法

思路
遍历链表,找出每个待删除节点的前一个节点。特殊情况:第一个节点就是待删除节点时,要单独操作。注意点:当输入为:[1,1] 时,按上面的思路删除第一个节点,剩下的链表的头节点又是待删除节点。
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;

}
使用虚拟头结点(统一头节点和其他节点的操作)简化代码:
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();
}
}

退出移动版