插入节点功能令人困惑

时间:2013-11-04 05:10:00

标签: c++ struct singly-linked-list

我正在尝试理解这个函数以按升序将元素插入到排序整数的链表中,但是,有些部分代码让我感到困惑......

Node* insert (int x, Node *p) {

 if (p==nullptr)
   return cons(x,nullptr); //inserts the new node at front of list,before node with nullptr?
 if (x < = p-> val)
    return cons(x,p); //this also inserts node at front of the list?
 //now the rest of the function is where I get confused...
 Node *prev=p; //so this is not allocating new memory, so what exactly does it mean?
 Node * after=prev->next; 
 //prev->next is pointing at whatever after is pointing to but after has no address?

 while (after!=nullptr && x > after->val) { //whats going on here?
   prev=after;
   after=after-> next;
 }

 prev->next=cons(x,after);
 return p;
}

1 个答案:

答案 0 :(得分:0)

Node* insert (int x, Node *p) {

 if (p==nullptr)
 return cons(x,nullptr); 
//inserts the new node at front of list,before node with nullptr?
if (x < = p-> val)
return cons(x,p); //this also inserts node at front of the list?

上面的代码负责在链表的开头插入新元素。有两种情况可以实现:

  1. 如果头部在这种情况下为p,则为NULL。
  2. 如果p指向的元素的值大于要插入的当前元素。
  3. 现在继续......

    //now the rest of the function is where I get confused...
    Node *prev=p; 
    //so this is not allocating new memory, so what exactly does it mean?
    

    这就像一个临时指针,可用于遍历链表。所以你将头部'p'存储在prev指针中。

    Node * after=prev->next; 
    //prev->next is pointing at whatever 
    //after is pointing to but after has no address?
    

    这是一个存储头部下一个元素的指针。

     while (after!=nullptr && x > after->val) { //whats going on here?
       prev=after;
       after=after-> next;
     }
     prev->next=cons(x,after);
     return p;
    }
    

    在这里,这看起来有些小问题。你可能想做这样的事情,而不是:

    While(prev->data >= inputdata && (after->data < inputdata || after == NULL)
    {
      //insert your inputdata here because it is greater than the previous but less than after
     // or after is NULL.
    }
    

    我希望这能澄清你的困惑。如果您有任何问题,请告诉我。