- 移除链表元素
题目链接
思路
1、引入一个新链表,先给头结点赋值,如果没有符合头结点的值直接返回空,有的话采用尾插法一个一个往里面插
2、引入一个新数组,再把数组的值给链表。
代码1
/**
* 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* l1=head;
ListNode* l2=nullptr;
ListNode* l3=l2;
while(l1){
if(l1->val != val){
ListNode* temp = new ListNode;
temp->val = l1->val;
l2 = temp;
l3 = l2;
l1 = l1->next;
break;
}
else l1 = l1->next;
}
if(l2==nullptr) return nullptr;
while(l1){
if(l1->val != val){
ListNode* temp = new ListNode;
temp->val = l1->val;
l2->next = temp;
l2 = l2->next;
l1 = l1->next;
}
else l1 = l1->next;
}
l1 = l3;
return l1;
}
};
代码2
/**
* 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) {
vector <int>vec;
ListNode* l1 = head;
while(l1){
if(l1->val!=val){
vec.push_back(l1->val);
}
l1 = l1->next;
}
ListNode* l2 = nullptr;
l1 = l2;
if(!vec.empty()){
ListNode* l3 = new ListNode;
int i = 0;
l3->val = vec[i];
l2 = l3;
l1 = l2;
i++;
while(i<vec.size()){
ListNode* l3 = new ListNode;
l3->val = vec[i];
l2->next = l3;
l2 = l3;
cout<<vec[i]<<endl;
i++;
}
}
return l1;
}
};
代码随想录思路
直接执行删除链表操作
class Solution {
public:
ListNode* removeElements(ListNode* head, int val) {
ListNode* dummyHead = new ListNode(0); // 设置一个虚拟头结点
dummyHead->next = head; // 将虚拟头结点指向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;
}
};