首页 > 解决方案 > last->next = temp 是如何工作的?

问题描述

这是 udemy 教程中显示链表的代码,我们将获取一个数组并将这些值存储在链表中。我不明白代码是如何工作的。在下面的代码中,我们存储下一个节点的地址 last->next=temp; 在我没有创建最后一个节点的地方工作,比如 last=new node; 我只创建了最后一个指针。我没明白 谁能给我解释一下它是如何工作的

#include <iostream>
using namespace std;
 
class Node{
public:
    int data;
    Node* next;
};
 
int main() {
 
    int A[] = {3, 5, 7, 10, 15};
 
    Node* head = new Node;
 
    Node* temp;
    Node* last;
 
    head->data = A[0];
    head->next = nullptr;
    last = head;
 
    // Create a Linked List
    for (int i=1; i<sizeof(A)/sizeof(A[0]); i++){
 
        // Create a temporary Node
        temp = new Node;
 
        // Populate temporary Node
        temp->data = A[i];
        temp->next = nullptr;
 
        // last's next is pointing to temp
        last->next = temp;
        last = temp;
    }
 
    // Display Linked List
    Node* p = head;
 
    while (p != nullptr){
        cout << p->data << " -> " << flush;
        p = p->next;
    }
 
    return 0;
}

标签: c++data-structureslinked-list

解决方案


找出指针的最好方法是用笔和纸画方框和箭头。

这是发生的事情的(悲伤的)ASCII再现:

head->data = A[0];
head->next = nullptr;
last = head;

head指向一个新创建的节点,并last指向同一个地方head

   head
    |
    v
+------+------+    
| data | next |
|      |(null)|
|      |      |
+------+------+
   ^
   |
  last

下一个,

// Create a temporary Node
temp = new Node;

// Populate temporary Node
temp->data = A[i];
temp->next = nullptr;

看起来像这样:

   head                 temp
    |                    |
    v                    v
+------+------+       +------+------+  
| data | next |       | data | next |
|      |(null)|       |      |(null)|
|      |      |       |      |      |
+------+------+       +------+------+
   ^
   |
  last

然后

last->next = temp;

更改next节点指向的成员(在第一次迭代中,这与指向last的节点相同):head

   head                 temp
    |                    |
    v                    v
+------+------+       +------+------+  
| data | next |       | data | next |
|      |   ---------->|      |(null)|
|      |      |       |      |      |
+------+------+       +------+------+
   ^
   |
  last

最后,您last指出最近创建的节点:

last = temp;

这使

   head                 temp
    |                    |
    v                    v
+------+------+       +------+------+  
| data | next |       | data | next |
|      |   ---------->|      |(null)|
|      |      |       |      |      |
+------+------+       +------+------+
                         ^
                         |
                        last

然后你从那里重复循环。


推荐阅读