题解 | #从单向链表中删除指定值的节点#
从单向链表中删除指定值的节点
https://www.nowcoder.com/practice/f96cd47e812842269058d483a11ced4f
#include <iostream>
using namespace std;
//节点类
class Node {
private:
int data;
Node* next;
public:
//构造函数
Node(const int data, Node* next = NULL);
//析构函数
~Node();
//获取节点值
const int getData(void);
//获取指针值(返回对指针的引用,便于修改)
Node*& Next(void);
};
Node::Node(const int data, Node* next) {
this->data = data;
this->next = next;
return;
}
Node::~Node() {
}
const int Node::getData(void) {
return this->data;
}
Node*& Node::Next(void) {
// TODO: 在此处插入 return 语句
return this->next;
}
//链表类
class List {
private:
//头节点
Node* head;
//长度
int length;
private:
//复制构造函数私有化,避免浅拷贝
List(const List&);
public:
//构造函数
List(const int num, const int data);
//析构函数
~List();
//在值为i的节点后插入值为j的节点
void insert(const int j, const int i);
//删除值为data的节点
void del(const int data);
//输出(<<运算符重载)
friend ostream& operator<<(ostream& cout, const List& list);
};
List::List(const int num, const int data) {
this->length = num;
this->head = new Node(data);
//插入后续节点
int a, b;
for (int i = 1; i < this->length; i++) {
cin >> a >> b;
this->insert(a, b);
}
//删除节点
cin >> a;
this->del(a);
return;
}
List::~List() {
Node* p = this->head;
while (p != NULL) {
Node* next = p->Next();
delete p;
p = next;
this->length--;
}
return;
}
void List::insert(const int j, const int i) {
Node* previous = this->head;
while (previous->getData() != i)
previous = previous->Next();
previous->Next() = new Node(j, previous->Next());
return;
}
void List::del(const int data) {
this->length--;
Node* previous = this->head;
//如果头节点就是要删除的节点
if (this->head->getData() == data) {
this->head = this->head->Next();
delete previous;
return;
}
//如果要删除的节点在后面
while (previous->Next()->getData() != data)
previous = previous->Next();
Node* p = previous->Next();
previous->Next() = previous->Next()->Next();
delete p;
return;
}
int main() {
int a, b;
while (cin >> a >> b) { // 注意 while 处理多个 case
List list(a, b);
cout << list << endl;
}
}
// 64 位输出请用 printf("%lld")
ostream& operator<<(ostream& cout, const List& list) {
//如果是空链表
if (list.head == NULL)
return cout;
cout << list.head->getData();
Node* p = list.head->Next();
while (p != NULL) {
cout << ' ' << p->getData();
p = p->Next();
}
// TODO: 在此处插入 return 语句
return cout;
}
