203. 移除链表元素
① 头节点的判断
② 指针移动的判断,判断他的 next,防止非法访问
/**
* 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)
{
ListNode* tmp = head;
head = head->next;
delete tmp;
}
ListNode* cur = head;
while(cur!=nullptr && cur->next!=nullptr)
{
if(cur->next->val == val)
{
ListNode* tmp = cur->next;
cur->next = cur->next->next;
delete tmp;
}
else
{
cur = cur->next;
}
}
return head;
}
};
206. 反转链表
① 头节点是否为空的判断
② 指针移动条件
③ 怎么保证指针方向移动后,已改变方向链表和链未改变方向链表的联系
class Solution {
public:
ListNode* reverseList(ListNode* head) {
if(head==nullptr)
{
return nullptr;
}
else
{
ListNode* cur = head;
ListNode* tmp = cur->next;
cur->next = nullptr;
while(tmp!=nullptr)
{
cur = tmp;
tmp = tmp->next;
cur->next = head;
head = cur;
}
return head;
}
}
};