LeetCode[203]移除链表元素
思路:
我是设置一个虚拟头节点,再设置一个用来遍历的节点,如果当前遍历的节点值和target一样,就让当前节点向下跳两个位置,如果不一样,就让当前节点走一步,设置虚拟头节点就是能省去一步判空操作
代码:
/**
* 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 hair = new ListNode(-1, head);
ListNode cur = hair;
while (cur.next != null) {
if (cur.next.val == val) {
cur.next = cur.next.next;
} else {
cur = cur.next;
}
}
return hair.next;
}
}