一、题目
给你一个链表的头节点 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
输出:[ ]
2、解题
1、原链表操作
先确定head是否等于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;
}
};
2、虚拟头节点
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;
}
};
3、虚拟头节点但不定义指针
定义dummyHead的时候,不定义指针,而是定义实体,这样在程序结束的时候就自动释放内存了,不用手动delete
class Solution {
public:
ListNode* removeElements(ListNode* head, int val) {
ListNode dummyHead; // 设置一个虚拟头结点
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;
}
}
return dummyHead.next;
}
};