【问题标题】:Why to use node pointer when creating a linked list?为什么在创建链表时使用节点指针?
【发布时间】:2020-11-05 14:41:52
【问题描述】:
struct Node
{
    int data;
    Node* next;
}

为什么我们不能像下面这样使用:

struct Node
{
    int data;
    int* next;
}

为什么我们必须创建 Node 类型的指针?我们还可以创建一个 int 类型的指针,因为在两种情况下传递的地址都是相同的。

【问题讨论】:

  • 因为下一个元素是struct Node 而不是int
  • @Jabberwocky 感谢您编辑 Jabber。是的,我同意下一个元素是一个节点,但是要到达那个地址,我们也可以使用下一个节点的整数的地址,因为节点地址从那里开始。
  • 是的,您可以这样做,但为什么呢?这会让一切变得更加复杂。
  • 不,我只是怀疑我的思维方式是否正确。无论如何谢谢@Jabberwocky
  • 为什么要使用任何类型?为什么还要使用C?只需编写程序集,其中所有内容都只是原始数据,没有额外的语义。

标签: c linked-list


【解决方案1】:

因为struct节点需要内存分配:

#include <stdio.h> 
#include <stdlib.h> 

struct Node{
 int data;
 struct Node* next;
};
struct Node* head = NULL;

void push(struct Node **node_ref, int data){
struct Node *newNode = malloc(sizeof(struct Node));
newNode->data = data;
newNode->next = (*node_ref);
(*node_ref) = newNode;
}
void displayList(struct Node* e){
    e = head;
    while(e != 0){
     printf("%d ", e->data);
     e = e->next;
    }
}
int main(){
head = NULL;
push(&head, 1);
push(&head, 2);
push(&head, 3);
displayList(head);
return 0;
}

结构节点应该与头结构相同,因为如果对象不同,C不能转换结构。

【讨论】:

  • 问题标记为 C,而不是 C++
  • @Jabberwocky 检查一下先生
  • 无需在 C 中强制转换 malloc 的返回值。并且答案应正确格式化。
  • 哦对,我太习惯用cpp了
  • 在 C++ 中你不应该使用 malloc。
【解决方案2】:

指针分为两种类型。有类型和无类型。 类型化指针指向特定类型,例如整数、浮点数、字符。

点赞int* next; // this pointer points to an integer.

无类型指针指向任何类型的数据类型。

struct node *next; // this points to a struct node data type which is the type of the next node.

因为前一个节点的指针保存着下一个节点的数据类型,而这里每个节点的数据类型都是struct node。

【讨论】:

    猜你喜欢
    • 2020-07-20
    • 2016-02-14
    • 2015-06-15
    • 1970-01-01
    • 2019-03-23
    • 2011-11-08
    • 1970-01-01
    • 2015-10-19
    相关资源
    最近更新 更多