Leetcode 203
class Solution {
public:
ListNode* removeElements(ListNode* head, int val) {
ListNode *dummyhead = new ListNode(0);
dummyhead->next = head;
ListNode *curr = dummyhead;
while(curr->next){
if(curr->next->val == val){
ListNode *tmp = curr->next;
curr->next = curr->next->next;
delete tmp;
}else{
curr = curr->next;
}
}
head = dummyhead->next;
delete dummyhead;
return head;
}
};
注意:
设置一个虚拟头节点(防止删除的元素是原本的头节点),此时return dummyhead->next
删除不需要的节点
第一遍写的时候直接写了curr = curr->next, 没有写else,会导致的问题:
1)当要删除最后一个元素的时候,此时curr->next已经是null了,再进入循环的时候curr->next就会报错
2)(虽然没有遇到,但感觉也会出问题) 如果有两个连续需要删除的节点,此时找不到前面的节点了
Leetcode 707 Design Linked List
class MyLinkedList {
public:
struct Node{
int val;
Node *next;
Node(int val){
this->val = val;
next = nullptr;
}
};
Node *dummyNode;
int size;
MyLinkedList() {
dummyNode = new Node(0);
size = 0;
}
int get(int index) {
Node *cur = dummyNode->next;
if(index < size){
while(index--){
cur = cur->next;
}
return cur->val;
}
return -1;
}
void addAtHead(int val) {
Node *tmp = dummyNode->next;
Node *newNode = new Node(val);
dummyNode->next = newNode;
newNode->next = tmp;
size ++;
}
void addAtTail(int val) {
Node *cur = dummyNode;
while(cur->next != nullptr){
cur = cur->next;
}
Node *newNode = new Node(val);
cur->next = newNode;
size ++;
}
void addAtIndex(int index, int val) {
if(index > size){
return;
}
Node *cur = dummyNode;
Node *newNode = new Node(val);
while(index > 0){
cur = cur->next;
index--;
}
newNode->next = cur->next;
cur->next = newNode;
size ++;
}
void deleteAtIndex(int index) {
if(index >= size)return;
Node *cur = dummyNode;
while(index--){
cur = cur->next;
}
Node *tmp = cur->next;
cur->next = cur->next->next;
delete tmp;
size--;
}
};
注意:
index和size在运行过程中具体的值和范围以及cur指向的值
不要忘记在add 和delete 的时候,修改size的值
tip: 0就是false
Leetcode 206 Reverse Linked List
1.双指针
class Solution {
public:
ListNode* reverseList(ListNode* head) {
ListNode *cur = head;
ListNode *pre = NULL;
while(cur != nullptr){
ListNode *tmp = cur->next;
cur->next = pre;
pre = cur;
cur = tmp;
}
return pre;
}
};
注意:return的值为pre, 此时cur已经为NULL
有两个指针分别指向current 和current 前一个值,移动指针改变箭头方向
2.递归
class Solution {
public:
ListNode* reverse(ListNode *cur, ListNode *pre){
if(cur == NULL){
return pre;
}
ListNode *tmp = cur->next;
cur->next = pre;
return reverse(tmp, cur);
}
ListNode* reverseList(ListNode* head) {
return reverse(head, NULL);
}
};
根据双指针解法而来:确定初始输入值为(head, cur); 停止条件为cur==NULL; 递归的值为新的cur和pre的值
文章详细介绍了如何使用C++在LeetCode上解决链表问题,包括203题(移除链表元素)、707题(设计链表)和206题(反转链表)。关键点在于利用虚拟头节点简化操作,以及正确处理边界条件和指针移动。对于链表的反转,提供了双指针和递归两种方法。

1846

被折叠的 条评论
为什么被折叠?



