0

我以这种方式实现了这个功能:

typedef node* List;
void DeleteFromPos(List &l, unsigned int p) {
    List lAux = l;
    unsigned int count = 1;

    while (lAux) {      
        if (p == 1) {
            while (l) {
                List del = lAux;
                lAux = lAux->next;
                delete del;
                del = NULL;
            }
            lAux = NULL;
        } else if (count < p-1) {
                lAux = lAux->next;
                count++;
        } else {
            List del = lAux->next;
            if (del) {
                lAux->next = del->next;
                delete del;
                del = NULL;
            } else
                lAux = NULL;
        }
    }
}

问题是当 p==1 时,在这种特殊情况下,所有元素都被删除,但看起来 l 指针最后仍然存在。我需要一些关于这个的建议。

编辑:有一些建议, p ==1 案例有他自己的循环,它很丑但它有效。

4

3 回答 3

1
void DeleteFromPos(List &l, unsigned int p)

我相信您通过node引用传递一个指针,以便如果要删除列表的头部,您可以更新指针本身,以便调用者可以看到此更改。然而你这样做:

List lAux = l;

这抛弃了这种潜力。如果p等于1,你应该这样做:

if (p == 1) {
    List del = l;
    l = l->next;   // <-- updates pointer that was passed by reference
    delete del;
}
于 2013-10-17T23:27:52.197 回答
1

指针 l 在你的函数中没有改变。您更改指针 lAux 但 l 保持其原始值。

于 2013-10-17T23:30:27.093 回答
1

Simplify your task by modularising. First have a function that deletes all elements in a list.

deleteList(List *&head) {
   while (head) {
      List *l = head->next;
      delete head;
      head = l;
   }
}

Note *& - reference to a pointer. Thus the function modifies head parameter.

Then have a function that locates n-th element. When you have n-th node call the above function.

If you really need to do the job in a single function then do something like:

deleteFromPosition(List *&head, unsigned int pos) {
  loop one: iterate through the list until n-th node is reached;
  loop two: iterate through the list tail deleting nodes as in the function above;
}

I am leaving details out for your exercise.

于 2013-10-17T23:35:26.760 回答