这段代码是一个简单的链表操作程序,包含了链表的创建、插入、删除、获取元素等基本操作。在主函数中,首先创建一个链表对象l1,然后调用create1()函数从输入中创建链表。接着调用search()函数,查找链表中偶数结点的个数,并输出结果。
代码逻辑上没有明显错误,但存在一些改进的空间。比如,在insert()和delete_element()函数中,动态申请了节点内存却没有及时释放;在get_element()函数中,动态申请了不必要的节点内存。
以下是修改后的代码:
#include <iostream>
using namespace std;
struct node {
int data;
node* next;
};
enum errorcode { success, overflow, underflow, rangeerror };
class list {
public:
list();
~list(); // 添加析构函数进行内存释放
int length() const;
errorcode get_element(const int i, int& x) const;
errorcode insert(const int i, const int x);
errorcode delete_element(const int i);
node* get_head() { return head; }
void create1(); // 头插法
void insert1(int x); // 增序排列
void display();
int search();
private:
int count;
node* head;
};
list::list()
{
head = new node;
head->next = head;
count = 0;
}
// 析构函数进行内存释放
list::~list()
{
node* p = head->next;
while (p != head)
{
node* temp = p->next; // 先保存下一个节点的指针
delete p; // 释放当前节点的内存
p = temp; // 指向下一个节点
}
delete head; // 最后释放头结点的内存
}
int list::length() const
{
node* p = head->next;
int n = 0;
while (p != head) {
p = p->next;
n++;
}
return n;
}
errorcode list::get_element(const int i, int& x) const
{
if (i < 1 || i > count)
return rangeerror;
node* p = head->next;
int j = 1;
while (j != i && p != nullptr) {
p = p->next;
j++;
}
if (p == nullptr)
return rangeerror;
x = p->data;
return success;
}
errorcode list::insert(const int i, const int x)
{
if (i < 1 || i > count + 1)
return rangeerror;
node* p = head;
int j = 0;
while (j != i - 1 && p != nullptr) {
p = p->next;
j++;
}
node* s = new node;
s->data = x;
s->next = p->next;
p->next = s;
count++;
return success;
}
errorcode list::delete_element(const int i)
{
if (i < 1 || i > count)
return rangeerror;
node* p = head;
int j = 0;
while (j != i - 1 && p != nullptr) {
p = p->next;
j++;
}
node* u = p->next;
p->next = u->next;
delete u;
count--;
return success;
}
void list::create1()
{
int x;
head->data = 0;
cout << "输入链表内容(输入-1结束):";
cin >> x;
while (x != -1) {
count++;
node* s = new node;
s->data = x;
s->next = head->next;
head->next = s;
cin >> x;
}
}
void list::insert1(int x)
{
node* u, * P;
P = head;
while (P->next != nullptr && P->next->data < x)
P = P->next;
if (P->next == nullptr || P->next->data > x) {
u = new node;
u->data = x;
u->next = P->next;
P->next = u;
count++;
}
}
void list::display()
{
node* p = head->next;
while (p != head) {
cout << p->data << " ";
p = p->next;
}
}
int list::search()
{
node* p = head->next;
int n = 0;
while (p != head) {
if (p->data % 2 == 0) {
n++;
}
p = p->next;
}
return n;
}
int main() {
list l1;
l1.create1();
cout << l1.search();
return 0;
}
这样修改后的代码更加规范,修复了内存泄漏问题,并添加了析构函数进行内存释放操作。
内容由零声教学AI助手提供,问题来源于学员提问