指向列表中元素VS元素本身的指针

Pointer to the element in the list VS element itself

本文关键字:元素 指针 VS 列表      更新时间:2023-10-16

我在网上找到了这个代码,我需要一点帮助。下面是代码:

#include<iostream>
using namespace std;
/* Linked list structure */
struct list {
struct list *prev;
int data;
struct list *next;
} *node = NULL, *first = NULL, *last = NULL, *node1 = NULL, *node2 = NULL;
class linkedlist {
public: 
    /* Function for create/insert node at the beginning of Linked list */
    void insert_beginning() {
        list *addBeg = new list;
        cout << "Enter value for the node:" << endl;
        cin >> addBeg->data;
        if(first == NULL) {
            addBeg->prev = NULL;
            addBeg->next = NULL;
            first = addBeg;
            last = addBeg;
            cout << "Linked list Created!" << endl;
        }

        else {
            addBeg->prev = NULL;
            first->prev = addBeg;
            addBeg->next = first;
            first = addBeg;
            cout << "Data Inserted at the beginning of the Linked list!" << endl;
        }
    }

我不明白的是,当他正在制作新的节点对象(在这种情况下,它是addBeg),他把一个指针操作符在它前面。我现在是怎么看的,对象创建的时候不应该在名字前不带" * "还有数据,指向下一个的指针和指向前一个的指针,不应该像指向列表中节点的指针那样只包含节点的地址,不包含任何其他数据?如果不是这样,那么是什么使指向列表中节点的指针与节点本身不同呢?

代码中的方法是正确的。您的理解是错误的,不能通过指向该节点的指针访问该节点的数据。

如果addBeg是指向new list返回的节点的指针,则该节点的数据可以使用操作符->访问:

list.data等价于addBeg->data

If that's not the case, then what is the thing that differs the pointer to the node in the list from the node itself ?

=比;addBeg是指向对象的指针,该对象由new List返回。

你没有正确解释这个c++声明…代码的含义

 list *addBeg = new list;

 list* addBeg;
 addBeg = new list;

list*也就是addBeg的类型。

注意,这些规则确实很奇怪,因为当*在逻辑上附加到第一个list以形成类型时,

的意义
list *a, b;

将声明a为"指向列表的指针",而b为"列表的实例"(因此含义附加到list,但星号本身附加到a)。

一些程序员在这方面做得很好:

  1. 他们总是在字体后面加上星号(在左边)
  2. 它们从不在同一个结构中声明两个变量

根据我的经验,在写了足够的代码之后,这个解释问题将消失,即使是C/c++声明的疯狂语法规则也会很容易阅读(至少在简单的情况下)。