leetcode203
给你一个链表的头节点 head
和一个整数 val
,请你删除链表中所有满足 Node.val == val
的节点,并返回 新的头节点 。
示例 1:
输入:head = [1,2,6,3,4,5,6], val = 6 输出:[1,2,3,4,5]
在C++中,如果两个指针指向同一个对象(在此上下文中,是链表中的节点),改变通过一个指针所进行的操作会影响到另一个指针看到的内容,因为它们实际上是共享同一块内存的。
通过影响指针的指向(prev->next),就可以改变链表的内容。
prev=prev->next/prev=curr只对指针移位,不改变链表
prev->next=curr改变了指针指向,所以会改变链表
using namespace std;
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 temp(-1);
temp.next = head;
ListNode* prev = &temp;
ListNode* curr = head;
while (curr != nullptr) {
if (curr->val == val) {
prev->next = curr->next;
curr = curr->next;
}
else {
prev = prev->next;
curr = curr->next;
}
//cout << head->next << endl;
}
head = temp.next;
//head = prev;
return head;
}
void showList(ListNode* temp) {
ListNode* temp1 = temp;
if (temp == nullptr) {
cout << "nullptr!" << endl;
return;
}
while (temp1->next != nullptr) {
cout << temp1->val << "->";
temp1 = temp1->next;
}
cout << temp1->val <<endl;
}
};
int main() {
Solution solution;
vector<int> n = {1,4,1,3,5};
ListNode* head = new ListNode(n[0]);
ListNode* temp = head;
for (int i = 1; i < n.size(); i++) {
head->next = new ListNode(n[i]);
head = head->next;
}
solution.showList(temp);
int val = 1;
ListNode* newhead = solution.removeElements(temp, val);
solution.showList(newhead);
return 0;
}
/*
int main() {
Solution solution;
vector<int> n = {1,4,1,3,5};
ListNode head(n[0]);
ListNode* temp = &head;
ListNode* temp1 = &head;
//另一种写法
//ListNode* head = new ListNode(n[0]);
//ListNode* temp = head;
for (int i = 1; i < n.size(); i++) {
temp1->next = new ListNode(n[i]);
temp1 = temp1->next;
}
solution.showList(temp);
int val = 1;
ListNode* newhead = solution.removeElements(temp, val);
solution.showList(newhead);
return 0;
}
*/
给出了创建节点的两种方法