题目地址:
https://leetcode.com/problems/remove-linked-list-elements/
删除值等于val的链表中的节点,返回新链表的head。
1、直接模拟删除节点的过程即可。代码如下:
class Solution {
public ListNode removeElements(ListNode head, int val) {
// 设一个dummy node,使得删除head和删除一般节点操作等同起来
ListNode dummy = new ListNode(0);
dummy.next = head;
ListNode cur = dummy;
while (cur.next != null) {
if (cur.next.val == val) {
// 如果cur下一个节点值为val,就跳过此节点
cur.next = cur.next.next;
} else {
cur = cur.next;
}
}
return dummy.next;
}
}
class ListNode {
int val;
ListNode next;
ListNode(int x) {
val = x;
}
}
时间复杂度 O ( n ) O(n) O(n),空间 O ( 1 ) O(1) O(1)。
法2:用递归。
public class Solution {
// 返回删除val后的链表的头结点
public ListNode removeElements(ListNode head, int val) {
// 如果链表为空,就直接返回
if (head == null) {
return head;
}
// 先删除后面的值为val的节点
head.next = removeElements(head.next, val);
// 然后分情况讨论删除head
if (head.val == val) {
return head.next;
} else {
return head;
}
}
}
时空复杂度 O ( n ) O(n) O(n)。
C++:
class Solution {
public:
using node_p = ListNode*;
node_p removeElements(node_p head, int val) {
node_p dummy = new ListNode(0), prev = dummy;
while (head) {
if (head->val != val) {
prev->next = head;
prev = prev->next;
}
head = head->next;
}
prev->next = 0;
return dummy->next;
}
};
时空复杂度与法1一样。