繁体   English   中英

当指针A指向指针B并且指针B改变时会发生什么

[英]What happens when pointer A points pointer B, and pointer B changed

我正在做单链表。 这是list_elem类:

    class list_elem{
     friend class single_list;
     private:
      int data;   /* Data of list element. */
      list_elem *next;   /* Next list element. */
     public:...

我有另一个名为single_list的类,其中包含我需要实现的成员方法

    class single_list{
     private:
     list_elem *head; /* List head. */
     public:
     void list_insert_front(list_elem *elem)
     ...

这是我困惑的代码,我想在列表的开头插入一个元素。

    void single_list::list_insert_front (list_elem *elem)
    {
        if (head == NULL)
        {
         head == elem;
        }
        else
        {
         elem->next = head;  //confused
         head == elem;       //confused
        }
    }

我想知道,在“head == elem”之后,elem-> next仍然会指向列表的第一个元素吗? 什么是elem->下一个指向现在?

我还考虑过另一个解决方案。 谁能告诉我这个是否正确?

    void single_list::list_insert_front (list_elem *elem)
    {
        if (head == NULL)
        {
         head == elem;
        }
        else
        {
         list_elem* temp;
         temp = head; 
         elem->next = temp;
         head == elem;
        }
    }

提前谢谢了

首先,您的代码错误地使用==代替= *

在头部插入元素的代码应如下所示:

elem->next = head; // This works when head==NULL, too
head = elem;

这样做的目的是将next elem插入第一行的前head ,并将elem作为第二行的新head

这是一个显示正在发生的事情的图表:

链表转换

  • 第一张图显示了添加粉红色的新元素之前的列表。
  • 第二张图显示了第一次赋值后的列表elem->next = head
  • 第三张图显示了列表的最终状态。

*我已经看到它相反地交换了太多次,但这是我第一次看到它像这样交换。

请参阅下面的评论:

void single_list::list_insert_front (list_elem *elem)
    {
        if (head == NULL)//head is the first reference in the linked-list
        {
         head == elem;//should be "=" not "==", since your linked-list is empty(no elements added yet) your head reference is assigned the reference value elem which should be null the first time. so your linked list structure at this points looks like head->null, head reference pointing to null.
        }
        else// at this point you are inserting the 1st to n elements
        {
         elem->next = head;  //Let's assume you previously inserted an element, Here you are assigning the reference that head was pointing to elem, this is necessary so we do not lose the reference of the element that was previously in the first position.  The structure looks like: "head->?", "new elemenent->reference of the previous element that was first"
         head == elem;       //Now we set the head reference equal to the reference of the new inserted element(which is now the first element), so the linked list structure looks like: head->[reference of new element]->[previous element] *
        }
    }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM