203.移除链表元素
链接:203.移除链表元素
难度:Easy
标签:递归、链表
简介:删除链表中等于给定值 val 的所有节点。
题解 1 - typescript
- 编辑时间:2021-06-05
- 执行用时:108ms
- 内存消耗:43.3MB
- 编程语言:typescript
- 解法介绍:初始化空头节点便于运算。
function removeElements(head: ListNode | null, val: number): ListNode | null {
if (head === null) return null;
const tempHead = new ListNode(0, head);
let p: ListNode | null = tempHead;
while (p !== null) {
let next: ListNode | null = p.next;
while (next !== null && next.val === val) next = next.next;
p.next = next;
p = next;
}
return tempHead.next;
}
题解 2 - java
- 编辑时间:2020-02-13
- 执行用时:1ms
- 内存消耗:40.1MB
- 编程语言:java
- 解法介绍:创建新链表,遍历节点,若存在符合的值则移除。
class Solution {
public ListNode removeElements(ListNode head, int val) {
ListNode newHead=new ListNode(0);
newHead.next=head;
ListNode tem=newHead;
while(tem!=null&&tem.next!=null) {
if(tem.next.val==val) {
tem.next=tem.next.next;
continue;
}
tem=tem.next;
}
return newHead.next;
}
}
题解 3 - c
- 编辑时间:2021-11-19
- 执行用时:8ms
- 内存消耗:7.9MB
- 编程语言:c
- 解法介绍:双指针。
struct ListNode* removeElements(struct ListNode* head, int val){
if (!head) return NULL;
while (head && head->val == val) head = head->next;
if (!head) return NULL;
struct ListNode *p = head;
struct ListNode *work = head;
while (work) {
work = work->next;
while(work && work->val == val) work = work->next;
p->next = work;
p = p->next;
}
return head;
}