而带指针的循环不起作用

时间:2014-12-05 22:26:54

标签: 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){
        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

3 个答案:

答案 0 :(得分:2)

你应该取消引用指针。现在,你指着他们的地址。看看这是否有助于解决您的问题。

答案 1 :(得分:0)

好的,问题(大部分)是代码:

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

答案 2 :(得分:0)

如果我理解你想要什么,你可以迭代你的列表并保存指针以便删除:

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