题目描述
给你一个链表的头节点 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
输出:[]
分析思路
此题是一道简单题,有两种方法。
第一种方法,分两种情况,分别考虑head节点的删除(用while,不能用if)和后面节点的删除,因为二者的删除方式不一样。
第二种方法,考虑加入一个dummyhead节点,加到head的前面,然后就按照一种方式进行删除即可。
c++代码如下,第一种方法代码:
/*** 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) {while(head!=nullptr && head->val==val){ // while!!!ListNode* tmp = head; // tmp暂存head,因为要删除head = head->next;delete tmp;}ListNode* cur = head;while(cur!=nullptr && cur->next!=nullptr){if(cur->next->val==val){ListNode* tmp = cur->next; // tmp暂存cur->next,因为要删除cur->next = cur->next->next;delete tmp;}else{cur = cur->next;}}return head;}
};
第二种方法代码如下,记得要随时释放不需要的节点空间。
/*** 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* dummyhead = new ListNode(0); // 定义一个dummy节点dummyhead->next = head;ListNode* cur = dummyhead;while(cur!=nullptr && cur->next!=nullptr){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;}
};
补充一个python版本的代码:
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:def removeElements(self, head: Optional[ListNode], val: int) -> Optional[ListNode]:dummyhead = ListNode()dummyhead.next = headcur = dummyheadwhile cur and cur.next:if cur.next.val == val:cur.next = cur.next.nextelse:cur = cur.nextreturn dummyhead.next
只能说python的代码是真的简洁。。。