2014-03-30 54 views
-3

很难理解这个节点是如何创建的,您可以逐步写出这组代码实际在做什么以及它们代表什么动作?创建并向链接列表添加新节点

void list::create_node(int value)  
{ 
    struct node *temp;// Please write in words the meaning of this statement 
    temp = new(struct node);// is this a dynamic node?)  
    temp->info = value;// is this value being assigned to this node? 

    if (last == NULL)// what is this set of code testing?? 
    {  
     last = temp;// who is this last; the node which has been created?  
     temp->next = last; // is the node pointing to itself being only one node? 
    } 
    else 
    { 
     temp->next = last->next;(((// What is this statement saying? 
     last->next = temp;// What is this statement saying? 
     last = temp;// What is this statement saying? 
    } 
} 
+0

我相信你至少明白这段代码的一行。请确切地确定你不了解的内容。 –

+0

我在代码旁边贴出了我的疑惑。 if语句节点的WH部分是“LAST” – ahmed

+1

这段代码已经几乎用普通英语了。 – bereal

回答

1
void list::create_node(int value)  
{ 

上述行声明创建与给定值的节点,并插入节点到列表的功能。必须检查代码以查看新节点的插入位置。

struct node *temp; 

声明指向节点的指针。内存尚未分配,只有稍后将使用的指针。

temp = new(struct node); 

分配内存,用于从动态(运行时)的存储器区域(也称为堆)的节点。调用node结构的构造函数初始化内存,如果一个构造函数存在。

指针temp现在指向node对象。

temp->info = value; 

此分配value数据字段,info。为了证实这个猜测,需要struct node的声明。

if (last == NULL) 
{ 

假设last是一个指针和指向最后一个节点,这个检查是寻找一个空列表。常见的实现是将指针值设置为空以标记列表的末尾。

上面的代码插入新的node作为最后一个节点。该last指针允许列表的末尾快速访问。这允许反向迭代而不必遍历所有链路来查找最后一个节点。

某些实现将next字段设置为空以指示列表的结尾,其他类似于此列的字段使其指向最后一个节点。

else 
{ 
    temp->next = last->next; 

此时,列表并非空白。
使新节点指向最后一个节点指向的同一节点。
通过绘制指向节点的节点框和箭头可以很好地理解这一点。

last->next = temp; 

更新的最后一个节点指向自身。请参阅上面的部分。

last = temp; 

更新指向最后一个(列表结束)节点的指针指向新节点。 } }

我建议你画一个链表,然后遍历这个算法几次,看看它是如何工作的。还请查看单链表数据类型。

最后一个节点的循环引用可能会让您感到困惑。这可能不是大多数书籍描述的标准实现,但它是有效的。

+0

它在很大程度上使图片清晰,我没有抓住代码图片,但现在好多了,我会画图并写下这个Algo – ahmed