簡體   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