![](/img/trans.png)
[英]what happens if I cast (a pointer to class A) to (a pointer to its subclass B) in c++
[英]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;
}
}
提前謝謝了
請參閱下面的評論:
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.