[抄题]:

Remove all elements from a linked list of integers that have value val.

Example
Given: 1 --> 2 --> 6 --> 3 --> 4 --> 5 --> 6,  val = 6
Return: 1 --> 2 --> 3 --> 4 --> 5

[暴力解法]:

时间分析:

空间分析:

[思维问题]:

  1. 链表结构可能会改变,忘记用dummy node了,做链表题时提前牢记
  2. 两个链表采用2个指针,一个链表用1个就够了

[一句话思路]:

[输入量]:空: 正常情况:特大:特小:程序里处理到的特殊情况:异常情况(不合法不合理的输入):

[画图]:

[一刷]:

  1. dummy初始化时,head = dummy是为了把head指针的指向从数字转移到dummy,使其名正言顺。
  2. 理解dummy一直是空节点,最后返回的还是dummy.next

[二刷]:

[三刷]:

[四刷]:

[五刷]:

[五分钟肉眼debug的结果]:

[总结]:

  1. 两个链表采用2个指针,一个链表用1个就够了

[复杂度]:Time complexity: O(n) Space complexity: O(1)

[英文数据结构或算法,为什么不用别的数据结构或算法]:

[关键模板化代码]:

ListNode dummy = new ListNode(0);
dummy.next = head;
head = dummy; //remove
while (head.next != null) {
if (head.next.val == val) {
head.next = head.next.next;
}else {
head = head.next;
}
} return dummy.next;

dummy node

[其他解法]:

[Follow Up]:

[LC给出的题目变变变]:

[代码风格] :

/**
* Definition for ListNode
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/ public class Solution {
/**
* @param head: a ListNode
* @param val: An integer
* @return: a ListNode
*/
public ListNode removeElements(ListNode head, int val) {
//dummy
ListNode dummy = new ListNode(0);
dummy.next = head;
head = dummy; //remove
while (head.next != null) {
if (head.next.val == val) {
head.next = head.next.next;
}else {
head = head.next;
}
} return dummy.next;
}
}
05-08 15:19