leetcode 每日一题 203. 移除链表元素
我的思路
使用指针,标记当前结点,如果当前结点的值等于给定的值,那么删除这个结点。怎么删除呢?这个结点的前一个结点的 next 直接指向这个结点的后一个结点,这样就可以删除掉本结点。
我使用两个指针,一个标记本结点,另一个标记本结点的前一个结点。当然啦,还有一个头结点,最后用于返回。
/**
* Definition for singly-linked list.
* function ListNode(val, next) {
* this.val = (val===undefined ? 0 : val)
* this.next = (next===undefined ? null : next)
* }
*/
/**
* @param {ListNode} head
* @param {number} val
* @return {ListNode}
*/
var removeElements = function (head, val) {
p = head; //指向头指针,最后用于返回
while (p != null && p.val == val) {
p = p.next == null ? null : p.next;
}
if (p == null) return p; //空链表,直接返回
pre = p; //指向本结点的前一个结点
temp = pre.next == null ? null : pre.next; //目前结点指针,用于查询更改
while (temp != null) {
if (temp.val == val) {
pre.next = temp.next == null ? null : temp.next;
temp = temp.next == null ? null : temp.next;
} else {
temp = temp.next;
pre = pre.next;
}
}
return p;
};
题解的其他思路
-
递归
因为链表具有递归性质,所以可以用递归解该题。var removeElements = function (head, val) { if (head === null) { //结点为空,返回;递归的终止条件。 return head; } head.next = removeElements(head.next, val); return head.val === val ? head.next : head; //判断head的值是否等于val,若是,则返回该节点的next,否则返回该结点。 };
-
迭代
其实感觉我用的方法就是迭代。不过感觉题解更加的精简。var removeElements = function (head, val) { const dummyHead = new ListNode(0); //虚拟头结点 dummyHead.next = head; let temp = dummyHead; //temp表示当前结点 while (temp.next !== null) { if (temp.next.val == val) { temp.next = temp.next.next; } else { temp = temp.next; } } return dummyHead.next; //返回虚拟头结点的next };
总结
- 又复习了链表操作,链表的定义具有递归的性质,在以后的做题过程中需要思考这一点。
- 在链表中,虚拟头结点在解题中很有必要。