// 删除链表节点
#include <iostream>
using namespace std;
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
class Solution {
public:
ListNode* deleteNode(ListNode* head, int val) {
if(head->val==val){
return head->next;
}
ListNode *cur=head;
// 找到目标节点
while((cur->next!=nullptr)&&(cur->next->val!=val)){
cur=cur->next;
}
// 删除目标节点
if(cur->next!=nullptr){
cur->next=cur->next->next;
}
return head;
}
};
int main(){
Solution sol;
ListNode* head = new ListNode(1);
head->next = new ListNode(2);
head->next->next = new ListNode(3);
// 打印创建的链表
ListNode* cur1 = head;
while(cur1 != nullptr) {
std::cout << cur1->val << " ";
cur1 = cur1->next;
}
std::cout << "-------"<<std::endl;
int val = 2;
head = sol.deleteNode(head, val);
// 输出删除节点后的链表
ListNode* cur = head;
while(cur != nullptr) {
std::cout << cur->val << " ";
cur = cur->next;
}
std::cout << std::endl;
return 0;
}
删除链表节点 代码
于 2024-05-20 13:49:56 首次发布