1 #include<iostream> 2 #include<cstring> 3 using namespace std; 4 5 struct student{ 6 int my_id; 7 char name[20]; 8 int my_age; 9 int my_score; 10 student *next = nullptr; 11 student() = default; 12 student(int id,const char *n,int age,int score) 13 {my_id = id;my_age = age;my_score = score;strcpy(name,n);} 14 ~student(){} 15 }; 16 struct stu_list{ 17 stu_list() = default; 18 ~stu_list(){}; 19 int creat_list(); 20 void show_list(); 21 int add_list(int num,const char *nn,int a,int s); 22 int remove_list(int nm); 23 int release_list(); 24 private: 25 student * head = nullptr; 26 }; 27 int stu_list::creat_list() 28 { 29 student *p = nullptr; 30 int ret; 31 while(1) 32 { 33 p = new student(); 34 if(!p){perror ("new error");return -1;} 35 ret=scanf("%d %s %d %d",&p->my_id,p->name,&p->my_age,&p->my_score); 36 if(ret < 0){break;} 37 if(head == nullptr){ 38 p->next = nullptr; 39 head = p; 40 }else{ 41 p->next = head; 42 head = p; 43 } 44 }//end while(1) 45 return 0; 46 47 } 48 void stu_list::show_list() 49 { 50 student *p = head; 51 printf("学号\t姓名\t\t年龄\t成绩\n"); 52 while(p) 53 { 54 printf("%d\t%s\t%d\t%d\n",p->my_id,p->name,p->my_age,p->my_score); 55 p = p->next; 56 } 57 } 58 int stu_list::add_list(int num,const char *nn,int a,int s) 59 { 60 student *p = nullptr; 61 p = new student(num,nn,a,s); 62 if(head == nullptr){ 63 p->next = nullptr; 64 head = p; 65 }else{ 66 p->next = head; 67 head = p; 68 } 69 return 0; 70 } 71 72 int stu_list::remove_list(int nm) 73 { 74 student *p,*q; 75 p = head;q = head; 76 while(p){ //查找要删除的结点 77 if( p->my_id == nm){break;} 78 q = p; 79 p = p->next; 80 }//end while 81 if(p != nullptr) 82 { 83 if(p == head) 84 { 85 if(p->next == nullptr){ 86 head = nullptr; 87 }else{ 88 head = head->next; 89 } 90 } 91 else{ 92 if(p->next == nullptr){q->next = nullptr;} 93 else{q->next = p->next;} 94 } 95 delete [] p; 96 return 0; 97 }//end first if 98 return -1; 99 } 100 /* 101 int stu_list::release_list() 102 { 103 student *p = head; 104 student *tmp = head; 105 while(p) 106 { 107 tmp = p->next; 108 delete [] p; 109 p = tmp; 110 } 111 } 112 */ 113 int main() 114 { 115 stu_list stu; 116 stu.creat_list(); 117 stu.show_list(); 118 cout<<"==========================================="<<endl; 119 stu.add_list(10006,"niwangba",21,65); 120 stu.show_list(); 121 cout<<"==========================================="<<endl; 122 stu.remove_list(10006); 123 stu.show_list(); 124 125 // stu.release_list(); 126 return 0; 127 }
为什么我的链表编译的时候能通过,但是运行的时候却显示:*** Error in `./list‘: free(): invalid pointer: 0x08ba20cc *** 已放弃 (核心已转储)?
求解决方法。还有就是这段代码能优化吗?
C++中单项链表的结点删除问题——为什么我的链表编译能过,但是运行的时候显示:*** Error in `./list': free(): invalid pointer: 0x08ba20cc *** 已放弃 (核心已转储)
时间: 2024-10-07 08:10:04