C++ 而带指针的循环不起作用
我有一个问题,我试图创建一个列表,删除一个最高值的数字,或者删除所有具有相同值的数字,如果该值在列表中是最高的。谢谢你给我的建议C++ 而带指针的循环不起作用,c++,list,pointers,C++,List,Pointers,我有一个问题,我试图创建一个列表,删除一个最高值的数字,或者删除所有具有相同值的数字,如果该值在列表中是最高的。谢谢你给我的建议 // n,n1,head,next - are pointers int j = 0; //this number helps to put pointer forward by one place while(n!=0){//should go through every digit of the list if(head == 0){ co
// n,n1,head,next - are pointers
int j = 0; //this number helps to put pointer forward by one place
while(n!=0){//should go through every digit of the list
if(head == 0){
cout << "list is empty" << endl;
}
else{
n = head;
n1=0; // n1 and n are pointers
while(n!=0){
if(n->sk == maxx){//searches for maximum digit in the list
break;
}
else{
n1=n;
n=n->next;
}
}
if(head == n){
head = head->next;
}
else{
n1->next = n->next;
}
delete n; // deletes the pointer holding the highest value
}
n = head; //problem is here or somewhere below
j++;
for(int i=0; i<j;i++){ // this loop should make the pointer point to the first
n = n->next; // number, then the second and so on until the end of list
} // and all the numbers inside the list with the value that
} // equals "maxx" should be deleted
//n,n1,head,next-是指针
int j=0//这个数字有助于将指针向前移动一个位置
而(n!=0){//应该遍历列表的每一位
如果(头==0){
下一步;
}
}
如果(头==n){
头部=头部->下一步;
}
否则{
n1->next=n->next;
}
删除n;//删除包含最高值的指针
}
n=头部//问题在这里或下面的某个地方
j++;
对于(int i=0;inxt;//number,然后是第二个,依此类推,直到列表末尾
}//以及列表中的所有数字,其值为
}//应删除等于“maxx”
您应该取消对指针的引用。现在,您正在指向它们的地址。看看这是否有助于解决您的问题。好的,问题(大部分)在于代码:
while(n!=0){
if(n->sk == maxx){
break;
}
else{
n1=n;
n=n->next;
}
}
如果找到maxx
值,则应删除该节点并继续搜索,不要break
。这样,此任务不需要太多代码
while (n != 0){
if (n->sk == maxx){
node *prev = n->prev; // The previous node.
node *tmp = n; // this assume you have a class node.
// temporaly holds the pointer to n.
prev->next = n->next; // Connect the previous node with the following one.
n = n->next; // advance n to the next node in the list.
delete tmp; // delete the node.
}
}
如果我正确理解了您想要的内容,您可以在列表上迭代并保存指针以便删除:
it = head;
pos = nullptr;
while (it != nullptr) {
if(it -> sk == maxx) {
pos = it; // save ptr
it = it -> next;
delete pos; // delete saved ptr
pos = nullptr;
}
}
如果列表是双面的,你的答案还会是一样的吗?双面的意思是循环的?我的意思是双链接列表,如果我的英语正确,你可以用指针前后移动。是的,我的答案仍然适用于双链接列表。你仍然可以将整个列表从头到尾移动。我的答案的主要问题是不要考虑到列表必须保持连接,我将立即修复它!