根据您提供的代码,我注意到在create1()
函数中,当输入-1时结束循环,但是在创建链表的过程中,并没有考虑到链表为空的情况。因此,在开始创建链表之前,需要将头结点指向自己来表示链表为空。
请尝试将以下行添加到list::list()
构造函数中:
head->data = 0;
另外,在 display()
函数中的循环条件应该是 p != head
而不是 p != NULL
。
修改后的代码如下:
#include <iostream>
using namespace std;
struct node {
int data;
node* next;
};
enum errorcode { success, overflow, underflow, rangeerror };
class list {
public:
list();
int length() const;
errorcode get_element(const int i, int& x) const;
node* locate(const 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;
head->data = 0; // 新增这行代码
}
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 {
node* p = new node;
p = head->next;
int j = 1;
while (j != i && p != NULL) {
p = p->next;
j++;
}
if (p == NULL)
return rangeerror;
x = p->data;
return success;
}
errorcode list::insert(const int i, const int x) {
node* p = new node;
p = head;
int j = 0;
while (j != i - 1 && p != NULL) {
p = p->next;
j++;
}
if (i < 1 || i > count + 1)
return rangeerror;
node* s = new node;
s->data = x;
s->next = p->next;
p->next = s;
count++;
return success;
}
errorcode list::delete_element(const int i) {
node* p = new node;
p = head;
int j = 0;
while (j != i - 1 && p != NULL) {
p = p->next;
j++;
}
if (i < 1 || i > count)
return rangeerror;
node* u = new node;
u= p->next;
p -> next= u -> next ;
delete u ;
count--;
return success;
}
void list::create1() {
int x;
cout << "输入链表内容(输入-1结束):";
cin >> x;
head->next=NULL;//创建空链表
while (x != -1) {
count++;
node* s=new node;
s -> data=x ;//存数据
if(head -> next==NULL){//如果是空链表就指向自己
head -> next=s ;
s -> next=head ;
}
else{
s -> next = head -> next;
head->next=s;
}
cin >> x;
}
}
void list::insert1(int x) {
node* u, * P;
P = head;
while (P->next != NULL && P->next->data < x)
P = P->next;
if (P->next == NULL || 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 count=0;
while(p !=head){
if(p -> data % 2==0){
count++ ;
p=p -> next ;
}
else{
p=p -> next ;
}
}
return count ;
}
int main() {
list l1;
l1.create1();
cout<<l1.search();
return 0;
}
请尝试运行修改后的代码,应该可以正确执行。
内容由零声教学AI助手提供,问题来源于学员提问