简体   繁体   English

带有指针的while循环不起作用

[英]While loop with pointers does not work

I have a problem, I am trying to create a list that deletes a highest value holding number, or all numbers with the same value if the value is highest in the list. 我有一个问题,我正在尝试创建一个列表,该列表删除一个拥有最高值的数字,或者删除列表中具有最高值的所有具有相同值的数字。 Thank you for any kind of tips. 感谢您提供的任何提示。

// 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

You should dereference the pointers. 您应该取消引用指针。 Right now, you're pointing to their addresses. 现在,您要指向他们的地址。 See if that helps resolve your problem. 查看是否有助于解决您的问题。

Ok, the problem (the most of it) is the code: 好的,问题(大部分)是代码:

   while(n!=0){
        if(n->sk == maxx){
            break;
        }
        else{
            n1=n;
            n=n->next;
        }
    }

If you find the maxx value you should delete that node and continue to searching, don't break . 如果找到maxx值,则应删除该节点并继续搜索,请不要break This way you don't need so much code for this task. 这样,您不需要太多代码即可完成此任务。

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.
    }
}

If I understand correctly what you want, you can just iterate over your list and save the pointer for deletion: 如果我正确理解了您想要的内容,则可以遍历列表并保存删除指针:

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;
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM