【问题标题】:inserting node function confusing插入节点功能混乱
【发布时间】:2013-11-04 05:09:59
【问题描述】:

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

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

【问题讨论】:

  • 理解指针操作的最好方法是用铅笔和纸画出来,例如作为箭头和框。

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


【解决方案1】:
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 指向的元素的值大于要插入的当前元素。

现在继续……

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

这是一个指针,用于存储 head 的下一个元素。

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-11-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-06-17
    • 1970-01-01
    • 1970-01-01
    • 2015-06-20
    相关资源
    最近更新 更多