代码随想录算法训练营第三天| 203.移除链表元素 、 707.设计链表 、206.反转链表

发布时间 2023-06-09 23:18:56作者: 博二爷

链表的构造:

link.h:

 1 #ifndef LINK_H
 2 #define LINK_H
 3 #include<vector>
 4 
 5 struct ListNode {
 6     int val;
 7     ListNode* next;
 8     ListNode() :val(0), next(nullptr) {}
 9     ListNode(int x) : val(x), next(nullptr) {}
10     ListNode(int x, ListNode* next) : val(x), next(next) {}
11 };
12 
13 class Solution {
14 public:
15     ListNode* removeElements(ListNode* head, int val);
16 
17 };
18 #endif
Link.h

实现链表:

1 #include<iostream>
2 #include"Link.h"
3 using namespace std;
4 
5 ListNode* Solution::removeElements(ListNode* head, int val)
6 {}
Complement

实现移除元素:

难点:

  1,因为给的head是不是空节点的head,一定要注意这一点

  2,需要自己定义一个空的头节点

  3,需要设置一个游标

  4,返回的时候,返回空节点的时候->用num

 1 ListNode* Solution::removeElements(ListNode* head, int val)
 2 {
 3     ListNode* DyHead = new ListNode();
 4     //注意 cur_ == head 
 5     DyHead->next = head;
 6     auto cur_ = DyHead;
 7 
 8     while (cur_->next != nullptr)
 9     {
10         if (cur_->next->val == val)
11         {
12             ListNode* mid = cur_->next;
13             cur_->next = mid->next;
14         }
15         // 不是的话,就下一个
16         else 
17         {
18             cur_ = cur_->next;
19         }
20     
21     }
22 
23     //不是原数组的head 而是 dyhead->next
24     return DyHead->next;
25 }