【发布时间】: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