【发布时间】:2018-08-27 09:09:45
【问题描述】:
这段代码对双向链表的解释是否正确?
我无法理解部分代码。这段代码发生了什么?
我已经解释了部分代码,但不太确定它是否正确。
void DoublyLinkedList::SortedInsert(const int& new_element) {
if (new_element != 0) { //creates new node np with value equal to new element
Node* np = new Node(new_element); //if new element is not equal to zero and if its not head, it points to both
head and tail
if (!Head)
{
Head = np;
Tail = np;
}
else if (new_element < Head->Element) //if new element less than element in Head np's next pointer pointing to
Head and Head prev pointer pointing to np and Head is pointing to np
{
np->Next = Head;
Head->Prev = np;
Head = np;
}
else //if new element is greater than Head we take cur node which is pointing
to Head's next pointer pointing to node after Head
{
Node *cur = Head->Next;
while ((cur) && (new_element >= cur->Element)) //new element greater than Node after Head,cur will point to cur's next pointer which is node after cur
cur = cur->Next;
if (cur)
{ // ?? whats happening here
np->Prev = cur->Prev;
np->Next = cur;
cur->Prev->Next = np;
cur->Prev = np;
}
else // ?? whats happening here
{
Tail->Next = np;
np->Prev = Tail;
Tail = np;
}
}
}
【问题讨论】:
-
我强烈建议您在浏览代码时使用笔和纸并绘制列表。使用箭头指向节点。操作将变得更加清晰。恕我直言,总是用链表和树来绘制。
-
@Thomas Matthews 我确实使用过纸上的绘图,但它变得非常混乱......你能帮助理解部分代码吗?
-
如果你不明白最后一部分告诉我,我会回答 tmrw
-
另外,你可以看看我的问题stackoverflow.com/questions/44530609/… ....即使我很挣扎,一旦它会让你更好地理解它。
标签: c++ pointers linked-list doubly-linked-list