从零开始学习c++,每天起码做一道leetcode题目,在此记录,希望最后能够有所收获!
今天开始进入链表的内容,以前学过,现在系统性地再重学一遍。
一、题目描述
给你一个链表的头节点 head 和一个整数 val ,请你删除链表中所有满足 Node.val == val 的节点,并返回 新的头节点 。
示例 1:
输入: head = [1,2,6,3,4,5,6], val = 6
输出: [1,2,3,4,5]
示例 2:
输入: head = [], val = 1
输出: []
示例 3:
输入: head = [7,7,7,7], val = 7
输出: []
二、思路分析
在通常移除链表元素的过程中,首先是要遍历链表,找到要移除的元素。同时记录要移除元素的前驱节点,以便在删除时更新其 next 指针。然后就是要删除元素。将前驱节点的 next 指针指向要删除元素的后继节点,从而将要删除的节点从链表中移除。
但按照上述这种方法就会发现,头节点需要单独进行处理,这其实是非常不方便的。所以第一种方法就是设置虚拟节点,在头节点前面再添加一个虚拟节点,这样即使是头节点也可以按照上面的方法来进行处理,
第二种方法就是将头节点和其他节点分开处理
三、AC代码
方法一:设置虚拟节点
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* temp=cur->next;
cur->next=temp->next;
delete temp;
}
else{
cur=cur->next;
}
}
return dummyhead->next;
}
};
方法二:在原链表上删除
class Solution {
public:
ListNode* removeElements(ListNode* head, int val) {
while(head!=NULL&&head->val==val){
ListNode* temp=head;
head=head->next;
delete temp;
}
ListNode* cur=head;
while(cur!=NULL&&cur->next!=NULL){
if(cur->next->val==val){
ListNode* temp=cur->next;
cur->next=temp->next;
delete temp;
}
else{
cur=cur->next;
}
}
return head;
}
};
四、总结
题目是比较简单的,不过有点忘记了。