这个是哪儿出了问题了

#include <iostream>
#include <iomanip>
#include <stdlib.h>
using namespace std;
struct node{
node(int x):data(x){}
int data;
struct node* next;
};


bool insert(node **root,int i,int x){
node *tmp = *root;
if(tmp == NULL || i == 0){
if(tmp == NULL){
tmp = new node(x);
tmp->next= NULL;
*root = tmp;
}else{
tmp = new node(x);
tmp->next = *root;
*root = tmp;
}
}else{
int j=0;
while(tmp && j < i-1){
j ++;
tmp  = tmp->next;
}
if(tmp == NULL){
cout <<"insert out of range "<< endl;
return false;
}
node *p1  = new node(x);
if(tmp->next == NULL){
tmp->next = p1;
p1->next = NULL;
}else{
p1->next = tmp->next;
tmp->next = p1;
}
}
return true;
}


bool remove_pos(node **root,int i){
int j=0;
node *tmp = *root;
if(tmp == NULL || i <0 ){
return false;
}else{
while(tmp && j < i -1){ 
tmp = tmp->next;
j ++;
}
if(tmp == NULL || tmp->next == NULL){
cout << "remove out of range" << endl;
return false;
}
//tmp->next is x
if(i == 0){
*root = tmp->next;
tmp->next = NULL;
delete tmp;
return true;
}else{
node *t = tmp->next;
tmp->next = t->next;
t->next = NULL;
delete t;
return true;
}
}


}


bool remove_value(node **root,int x){
int j=0;
node *tmp = *root;
if(tmp == NULL){
cout << "list is empty " << endl;
return false;
}
node *t= NULL;
while(tmp){
if(tmp->data == x){
break;
}
t = tmp;
tmp = tmp->next;
}
if(tmp == NULL){
cout << "x not in the list" << endl;
return false;
}else{
if(t == NULL){
delete tmp;
}else{
t->next  = tmp->next;
delete tmp;
}
}
return true;
}


int get_size(node **root){
int i=0;
node *tmp = *root;
while(tmp){
i++;
tmp = tmp->next;
}
return i;
}




void print(node **root){
node *tmp= *root;
int i=0;
while(tmp){
i ++;
cout << setw(5) << tmp->data;
if(i % 10 == 0){
cout << endl;
}
tmp = tmp->next;
}
}






void test1(){
node *root;
srand(NULL);
int all[100];
#if 1
cout << "init list" << endl << endl;


for(int i=0;i < 100;i ++){
all[i] = rand() % 1987;
insert(&root,0,all[i]);
}
#endif


#if 1
cout << "print all" << endl<< endl;
print(&root);
#endif


#if 1
cout  <<  "print size"<< endl;
cout << get_size(&root)<< endl;;
#endif


#if 0
cout << "remove_value" << endl << endl;
for(int i=0;i < 100;i ++){
remove_value(&root,all[i]);
}
#endif


#if 0
cout << "remove_pos" << endl << endl;
for(int i=0;i < 100;i ++){
cout << remove_pos(&root,0)<< endl;
}
#endif

}


如果在调用remove_value或者remove_pos之前调用了get_size或者print,则会出错,

如果没有调用get_size或者print直接调用remove_pos或者remove_value,则不会出错,原因是什么???呢


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值