题目来源:LeetCode ( 203 )—移除链表元素
定义虚拟头结点; 使得一个结点作为标记去遍历链表;取到的是待删除结点的前一个结点,将匹配到 val值的结点删除后,删除结点的前一个结点 指向 变为删除结点的后一个结点.而删除的结点指向为null
public class Solution {
class ListNode {
int val;
ListNode next;
ListNode() {}
ListNode(int val) { this.val = val; }
ListNode(int val, ListNode next) { this.val = val; this.next = next; }
}
private ListNode head;
public Solution() {
head=null;
}
public ListNode removeElements(ListNode head, int val) {
ListNode dummyHead = new ListNode(Integer.MIN_VALUE);
dummyHead.next = head;
ListNode preNOde = dummyHead;
while (preNOde.next != null) {
int result = preNOde.next.val;
if (result==(val)) {
ListNode delNode = preNOde.next;
preNOde.next = delNode.next;
delNode.next = null;
} else {
preNOde = preNOde.next;
}
}
return dummyHead.next;
}
}
|