【链表专题】剑指 Offer 18. 删除链表的节点
本问题对应课程链接:剑指offer刷题第三期
要求:
1、请打卡你的解题代码,如果能简单说一下思路则简单说一下思路,请代码不要直接抄袭复制我题解区给的代码哦。
2、给出你代码所用的时间复杂度和空间复杂度
第一次打卡注意:打卡的时候,代码支持 markdown 格式,并且必须要指定语言,比如

本问题对应课程链接:剑指offer刷题第三期
要求:
1、请打卡你的解题代码,如果能简单说一下思路则简单说一下思路,请代码不要直接抄袭复制我题解区给的代码哦。
2、给出你代码所用的时间复杂度和空间复杂度
第一次打卡注意:打卡的时候,代码支持 markdown 格式,并且必须要指定语言,比如

共以下 105 个回答
###C++实现
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode deleteNode(ListNode* head, int val) {
if(headNULL) return NULL;
if(head->valval) return head->next;
ListNode* pre=head;
ListNode* temp=head->next;
while(temp!=NULL)
{
if(temp->valval)
{
pre->next=temp->next;
return head;
}
temp=temp->next;
pre=pre->next;
}
return head;
}
};
方法:双指针
时间复杂度O(n)
空间复杂度O(1)
我这个是删除所有值为val的节点
打卡:
class Solution {
public ListNode deleteNode(ListNode head, int val) {
if(headnull){
return null;
}
if(head.valval){
return head.next;
}
ListNode helper=head;
while(helper.next!=null){
if(helper.next.valval){
helper.next=helper.next.next;
break;
}else{
helper=helper.next;
}
}
return head;
}
}
”’java
class Solution {
public ListNode deleteNode(ListNode head, int val) {
if(head null){
return null;
}
if(head.val val){
return head.next;
}
//给一个虚拟头结点
ListNode pre = new ListNode(0);
pre.next = head;
ListNode now = head;
while(now != null){
if(now.val val){
pre.next = now.next;
break;
}else{
pre = now;
now = now.next;
}
}
return head;
}
}
c++ 虚拟头节点
class Solution {
public:
ListNode* deleteNode(ListNode* head, int val) {
ListNode* dummyHead = new ListNode(1);
dummyHead->next = head;
ListNode* cur = dummyHead;
while (cur->next != NULL) {
if(cur->next->val val) {
cur->next = cur->next->next;
break;
} else {
cur = cur->next;
}
}
head = dummyHead->next;
delete dummyHead;
return head;
}
};