Description 输入n个整数,先按照数据输入的顺序建立一个带头结点的单链表,再输入一个数据m,将单链表中的值为m的结点全部删除。分别输出建立的初始单链表和完成删除后的单链表。 Input 第一行输入数据个数n; 第二行依次输入n个整数; 第三行输入欲删除数据m。 Output 第一行输出原始单链表的长度; 第二行依次输出原始单链表的数据; 第三行输出完成删除后的单链表长度; 第四行依次输出完成删除后的单链表数据。 Sample Input 10 56 25 12 33 66 54 7 12 33 12 12 Sample Output 10 56 25 12 33 66 54 7 12 33 12 7 56 25 33 66 54 7 33 需要代码
时间: 2024-03-01 10:53:48 浏览: 62
好的,以下是实现该功能的C++代码:
```c++
#include <iostream>
using namespace std;
// 定义单链表结点
struct ListNode {
int val;
ListNode* next;
ListNode(int x) : val(x), next(nullptr) {}
};
// 定义带头结点的单链表
class LinkedList {
private:
ListNode* head;
public:
LinkedList() {
head = new ListNode(0);
}
~LinkedList() {
ListNode* cur = head;
while (cur != nullptr) {
ListNode* temp = cur;
cur = cur->next;
delete temp;
}
head = nullptr;
}
void insert(int x) {
ListNode* cur = head;
while (cur->next != nullptr) {
cur = cur->next;
}
cur->next = new ListNode(x);
}
void remove(int x) {
ListNode* cur = head->next;
ListNode* pre = head;
while (cur != nullptr) {
if (cur->val == x) {
pre->next = cur->next;
delete cur;
cur = pre->next;
} else {
pre = cur;
cur = cur->next;
}
}
}
void print() {
ListNode* cur = head->next;
while (cur != nullptr) {
cout << cur->val << " ";
cur = cur->next;
}
cout << endl;
}
int length() {
int cnt = 0;
ListNode* cur = head->next;
while (cur != nullptr) {
cnt++;
cur = cur->next;
}
return cnt;
}
};
int main() {
int n;
cin >> n;
// 建立初始单链表
LinkedList list;
for (int i = 0; i < n; i++) {
int x;
cin >> x;
list.insert(x);
}
// 删除结点
int m;
cin >> m;
list.remove(m);
// 输出结果
cout << list.length() << endl;
list.print();
return 0;
}
```
该代码建立了带头结点的单链表,实现了插入和删除结点的功能,并且在输出时分别输出了链表长度和数据。你可以将此代码复制到本地编译运行,以便更好地理解。