**203.移除链表元素 **
leetcode链接:https://leetcode.cn/problems/remove-linked-list-elements/
题目描述:给你一个链表的头节点 head 和一个整数 val ,请你删除链表中所有满足 Node.val == val 的节点,并返回 新的头节点 。
核心思路:对链表删除的掌握程度。可以直接删除,需要考虑目标是否在头节点。或者创建虚拟头节点来解决,更为简洁。
普通方法:分别对头节点以及非头节点进行删除
点击查看代码
class Solution {
public:
ListNode* removeElements(ListNode* head, int val) {
while(head!=NULL && head->val==val){
ListNode* tmp = head;
head = head->next;
delete tmp;
}
ListNode* cur = head;
while(cur!=NULL && cur->next!=NULL){
if(cur->next->val == val){
ListNode* tmp = cur->next;
cur->next = cur->next->next;
delete tmp;
}
else cur = cur->next;
}
return head;
}
};
点击查看代码
class Solution {
public:
ListNode* removeElements(ListNode* head, int val) {
ListNode* dummyhead = new ListNode(0);
dummyhead->next = head;//创建的虚拟节点要指向头节点
ListNode* cur = dummyhead;//从头节点开始遍历
while(cur->next!=NULL){
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;
}
};
点击查看代码
class MyLinkedList {
public:
struct LinkedNode{
int val;
LinkedNode* next;
LinkedNode(int x): val(x), next(nullptr){}
};
MyLinkedList() {
dummyhead = new LinkedNode(0);
size = 0;
}
int get(int index) {
if(index > size-1 || index < 0){
return -1;
}
LinkedNode* cur = dummyhead->next;
while(index--){
cur = cur->next;
}
return cur->val;
}
void addAtHead(int val) {
LinkedNode* newNode = new LinkedNode(val);
newNode->next = dummyhead->next;
dummyhead->next = newNode;
size++;
}
void addAtTail(int val) {
LinkedNode* newNode = new LinkedNode(val);
LinkedNode* cur = dummyhead;
while(cur->next != nullptr){
cur = cur->next;
}
cur->next = newNode;
size++;
}
void addAtIndex(int index, int val) {
LinkedNode* cur = dummyhead;
LinkedNode* newNode = new LinkedNode(val);
if(index < 0)index = 0;
if(index > size)return ;
while(index--){
cur = cur->next;
}
newNode->next = cur->next;
cur->next = newNode;
size++;
}
void deleteAtIndex(int index) {
LinkedNode* cur = dummyhead;
if(index < 0 || index >= size)return ;
while(index--){
cur = cur->next;
}
LinkedNode* tmp = cur->next;
cur->next = cur->next->next;
delete tmp;
tmp = nullptr;
size--;
}
private:
int size = 0;
LinkedNode* dummyhead;
};
点击查看代码
class Solution {
public:
ListNode* reverseList(ListNode* head) {
ListNode* cur = head;
ListNode* pre = nullptr;
while(cur){
ListNode* tmp = cur->next;//局部变量,无需手动删除
cur->next = pre;
pre = cur;
cur = tmp;
}
return pre;
}
};
递归法:主要要注意调用递归传入的值
点击查看代码
class Solution {
public:
ListNode* reverse(ListNode* cur,ListNode* pre){
if(cur==NULL)return pre;//先判断cur是否为空,防止后续出现空指针
ListNode* tmp = cur->next;
cur->next = pre;
return reverse(tmp,cur);//注意这里传入的值
};
ListNode* reverseList(ListNode* head) {
return reverse(head,NULL);
}
};