链表的一些基础知识:链表的结点由两部分组成——数据域和指针域,数据域存放结点要存储的数据,指针域指向下一个结点的地址。可分为单链表、双链表和循环链表。(关于头节点是否要存数据,力扣上的会存。)
常用的解题思路:设置一个虚拟头节点。
一、LeetCode题 203.移除链表元素 203. 移除链表元素 - 力扣(LeetCode)
题目描述:
思路:设置一个虚拟头节点,作为新的头节点。这样在删除列表元素时,如果要删除的是头结点,不需要特殊处理。
代码:
/**
* 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) {
ListNode* dummyhead = new ListNode;
dummyhead -> next = head;
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->next;
delete(dummyhead);
return head;
}
};
1、new 用法:用来申请动态空间,返回类型为同变量类型的指针(在堆区开辟内存),需要手动 delete 释放。
2、用 new 来创建链表中的新结点,用来枚举结点的变量 cur 和用于释放内存的变量 tmp 不需要用 new 来创建。
二、 LeetCode题 707.设计链表 707. 设计链表 - 力扣(LeetCode)
题目描述:包含了链表的常见操作,较为简单。
代码:
class MyLinkedList {
public:
// 定义链表结构体
struct MyListNode{
int val;
MyListNode *next;
MyListNode(int x):val(x),next(nullptr){}
};
MyLinkedList() {
// 虚拟头节点
_dummyhead = new MyListNode(0);
// 链表长度
_size = 0;
}
int get(int index) {
// 判断下标是否有效, 下标从0开始
if(index < 0 || index > _size - 1){
return -1;
}
MyListNode* cur = _dummyhead->next;
while(index > 0){
cur = cur->next;
index--;
}
return cur->val;
}
void addAtHead(int val) {
MyListNode* newhead = new MyListNode(val);
newhead->next = _dummyhead->next;
_dummyhead->next = newhead;
_size++;
}
void addAtTail(int val) {
MyListNode* newtail = new MyListNode(val);
MyListNode* cur = _dummyhead;
while(cur->next != nullptr){
cur = cur->next;
}
cur->next = newtail;
_size++;
}
void addAtIndex(int index, int val) {
if(index > _size) return;
MyListNode* newnode = new MyListNode(val);
MyListNode* cur = _dummyhead;
while(index > 0){
cur = cur->next;
index--;
}
newnode->next = cur->next;
cur->next = newnode;
_size++;
}
void deleteAtIndex(int index) {
if(index < 0 || index > _size - 1) return;
MyListNode* cur = _dummyhead;
while(index > 0){
cur = cur->next;
index--;
}
MyListNode* tmp = cur->next;
cur->next = cur->next->next;
delete(tmp);
//被delete后的指针tmp的值(地址)并非就是NULL,而是随机值。也就是被delete后,
//如果不再加上一句tmp=nullptr,tmp会成为乱指的野指针
tmp = nullptr;
_size--;
}
private:
// 成员变量
MyListNode* _dummyhead;
int _size;
};
/**
* Your MyLinkedList object will be instantiated and called as such:
* MyLinkedList* obj = new MyLinkedList();
* int param_1 = obj->get(index);
* obj->addAtHead(val);
* obj->addAtTail(val);
* obj->addAtIndex(index,val);
* obj->deleteAtIndex(index);
*/
c++中,变量名加前缀 ‘_’ 是一种命名约定,用于区分类的成员变量与局部变量。
本文根据代码随想录顺序刷题。代码随想录 (programmercarl.com)