当前位置:网站首页>2.1 链表——移除链表元素(Leetcode 203)
2.1 链表——移除链表元素(Leetcode 203)
2022-06-12 07:58:00 【Amoni_】
直接使用原来的链表来进行移除节点操作:
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode() : val(0), next(nullptr) {} * ListNode(int x) : val(x), next(nullptr) {} * ListNode(int x, ListNode *next) : val(x), next(next) {} * }; */
class Solution {
public:
ListNode* removeElements(ListNode* head, int val) {
// 删除头结点
while(head != nullptr && head->val == val){
// 不等于空指针 且 头结点值等于val
ListNode *temp = head;
head = head->next;
delete temp;
}
// 删除非头节点
ListNode *cur = head; // 初始化当前指针为头指针
while(cur != nullptr && cur->next != nullptr){
// 不等于空指针 且 不是尾节点
if(cur->next->val == val){
// 头结点已经进行过判断,因此判断下一个节点的val
ListNode *temp = cur->next;
cur->next = cur->next->next;
delete temp;
}
else{
cur = cur->next;
}
}
return head;
}
};
设置一个虚拟头结点在进行移除节点操作:
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode() : val(0), next(nullptr) {} * ListNode(int x) : val(x), next(nullptr) {} * ListNode(int x, ListNode *next) : val(x), next(next) {} * }; */
class Solution {
public:
ListNode* removeElements(ListNode* head, int val) {
// 创建并初始化dummyHead
ListNode* dummyHead = new ListNode(0);
dummyHead->next = head;
// 初始化当前指针为dummyHead
ListNode* cur = dummyHead;
while(cur->next != nullptr){
if(cur->next->val == val){
ListNode* tmp = cur->next;
cur->next = cur->next->next;
delete tmp;
}
else{
cur = cur->next;
}
}
// 还原Head,并删除dummyHead
head = dummyHead->next;
delete dummyHead;
return head;
}
};
总结:设置一个虚拟头结点,使得头结点变成了普通节点,操作上变得更简单一致
边栏推荐
猜你喜欢

The project file contains toolsversion= "14.0". This toolset may be unknown or missing workarounds

System service configuration service - detailed version

Cookies and sessions

Chapter V - message authentication and digital signature

Literature reading: deep neural networks for YouTube recommendations

Multithread decompression of tar

谋新局、促发展,桂林绿色数字经济的头雁效应

Topic 1 Single_ Cell_ analysis(4)

vscode 1.68变化与关注点(整理导入语句/实验性新命令中心等)

Architecture and performance analysis of convolutional neural network
随机推荐
Principes et exemples de tâches OpenMP
Servlet advanced
Mathematical Essays: Notes on the angle between vectors in high dimensional space
Architecture and performance analysis of convolutional neural network
2021.10.24-25 scientific research log
Visual studio code batch comment and uncomment
[redistemplate method details]
[RedisTemplate方法详解]
Search and rescue strategy of underwater robot (FISH)
Improvement of hash function based on life game (continued 1)
『Three.js』辅助坐标轴
20220526 损失函数
OpenMP task 原理与实例
LeetCode笔记:Biweekly Contest 79
Topic 1 Single_ Cell_ analysis(3)
2021.11.2 scientific research log
Solve the problem of uploading sftporg apache. commons. net. MalformedServerReplyException: Could not parse respon
Solve mapper duplication problem in reverse engineering
2021.11.3-7 scientific research log
Servlet