代码随想录算法训练营第3天|203. 移除链表元素、707. 设计链表、 206. 翻转链表
203. 移除链表元素
提交代码(方法-迭代)
class Solution {
public:
ListNode* removeElements(ListNode* head, int val) {
ListNode* dummy = new ListNode();
dummy -> next = head;
ListNode* cur = dummy;
while(cur -> next != nullptr)
{
if(cur -> next -> val == val)
cur -> next = cur -> next -> next;
else
cur = cur -> next;
}
return dummy -> next;
}
};
解答代码(方法-迭代)
class Solution {
public:
ListNode* removeElements(ListNode* head, int val) {
struct ListNode* dummyHead = new ListNode(0, head);
struct ListNode* temp = dummyHead;
while (temp->next != NULL) {
if (temp->next->val == val) {
temp->next = temp->next->next;
} else {
temp = temp->next;
}
}
return dummyHead->next;
}
};
707. 设计链表
提交代码(方法)
解答代码(方法)
206. 反转链表
提交代码(方法)
class Solution {
public:
ListNode* reverseList(ListNode* head) {
ListNode* prev = nullptr;
ListNode* cur = head;
while (cur) {
ListNode* next = cur->next;
cur->next = prev;
prev = cur;
cur = next;
}
return prev;
}
};
解答代码(方法)
class Solution {
public:
ListNode* reverseList(ListNode* head) {
ListNode* prev = nullptr;
ListNode* curr = head;
while (curr) {
ListNode* next = curr->next;
curr->next = prev;
prev = curr;
curr = next;
}
return prev;
}
};
总结
日期: 2023 年 3 月 17 日
学习时长: 1 h 0 m
难度:
★
\bigstar
★
累计完成题目数量: 8
距离目标还有数量: 292
小结:
- 关于移除链表元素中的if是有else对应的,不然就会漏删某些元素。