给你一个链表的头节点 head 和一个整数 val ,请你删除链表中所有满足 Node.val == val 的节点,并返回 新的头节点

示例 1:

移除链表元素-203 - 图1

  1. Input: head = [1,2,6,3,4,5,6], val = 6
  2. Output: [1,2,3,4,5]

示例 2:

  1. Input: head = [], val = 1
  2. Output: []

示例 3:

  1. Input: head = [7,7,7,7], val = 7
  2. Output: []

提示:

  • 列表中的节点在范围 [0, 10] 内;
  • 1 ≤ Node.val ≤ 50;
  • 0 ≤ k ≤ 50

思路

首先,如果前导元素是val,用一个while()循环把前导元素都删掉;

然后新建一个cur_node和一个next_node指针,用于指向当前节点下一个节点

最后就是模拟删除链表的操作了,考验读者代码实现的能力。

代码

Cpp:

  1. // 24ms, 14.8MB
  2. /**
  3. * Definition for singly-linked list.
  4. * struct ListNode {
  5. * int val;
  6. * ListNode *next;
  7. * ListNode() : val(0), next(nullptr) {}
  8. * ListNode(int x) : val(x), next(nullptr) {}
  9. * ListNode(int x, ListNode *next) : val(x), next(next) {}
  10. * };
  11. */
  12. class Solution {
  13. ListNode* tmp_node;
  14. public:
  15. ListNode* removeElements(ListNode* head, int val) {
  16. if( head == nullptr ) return nullptr;
  17. // Skip leading target
  18. while( head != nullptr && head->val == val ) {
  19. tmp_node = head;
  20. head = head->next;
  21. delete tmp_node;
  22. }
  23. if( head == nullptr ) return nullptr;
  24. if( head->next == nullptr ) return head;
  25. ListNode* cur_node = head;
  26. ListNode* next_node = head->next;
  27. while( cur_node != nullptr && next_node != nullptr ) {
  28. if( next_node->val == val ) { // delete a node
  29. tmp_node = next_node;
  30. next_node = next_node->next;
  31. cur_node->next = next_node;
  32. delete tmp_node;
  33. }
  34. else { // move forward
  35. cur_node = cur_node->next;
  36. next_node = next_node->next;
  37. }
  38. }
  39. return head;
  40. }
  41. };

Rust:

  1. // 4ms, 2.6MB
  2. // Definition for singly-linked list.
  3. // #[derive(PartialEq, Eq, Clone, Debug)]
  4. // pub struct ListNode {
  5. // pub val: i32,
  6. // pub next: Option<Box<ListNode>>
  7. // }
  8. //
  9. // impl ListNode {
  10. // #[inline]
  11. // fn new(val: i32) -> Self {
  12. // ListNode {
  13. // next: None,
  14. // val
  15. // }
  16. // }
  17. // }
  18. impl Solution {
  19. pub fn remove_elements(head: Option<Box<ListNode>>, val: i32) -> Option<Box<ListNode>> {
  20. if let None = head {
  21. return None;
  22. }
  23. let mut head: Option<Box<ListNode>> = head;
  24. let mut cur_node = head.as_mut().unwrap();
  25. while let Some(i) = cur_node.next.as_mut() {
  26. if i.val == val {
  27. cur_node.next = i.next.take();
  28. } else {
  29. cur_node = cur_node.next.as_mut().unwrap();
  30. }
  31. }
  32. let last_1_standing = head.as_mut().unwrap();
  33. if last_1_standing.val == val {
  34. return head.unwrap().next;
  35. }
  36. head
  37. }
  38. }