题目:203.移除链表元素
解析:2.5 练习时长两年半
解题思路
使用虚拟头节点,判定下一个节点是否为val,若为val,则删除下一个节点
代码
/**
* 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; }
* }
*/
class Solution {
public ListNode removeElements(ListNode head, int val) {
ListNode dummy = new ListNode(-1, head);
ListNode cur = dummy;
while (cur.next != null){
if (cur.next.val == val){
cur.next = cur.next.next;
}else{
cur = cur.next;
}
}
return dummy.next;
}
}
总结
没试过不适用虚拟头节点
/**
* 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; }
* }
*/
class Solution {
public ListNode removeElements(ListNode head, int val) {
while (head != null && head.val == val){
head = head.next;
}
if (head == null)
return head;
ListNode cur = head;
while (cur.next != null){
if (cur.next.val == val)
cur.next = cur.next.next;
else
cur = cur.next;
}
return head;
}
}