C语言 创建单链表的算法

您所在的位置:网站首页 c语言temp函数 C语言 创建单链表的算法

C语言 创建单链表的算法

2022-12-19 08:07| 来源: 网络整理| 查看: 265

箭头运算符(->)用于使用指向结构的指针访问该结构的成员。它等效于使用点运算符(.)来存取结构的成员,但增加了取消指涉结构指标的步骤。例如,如果p是struct node的指标,那么p->DATA等于(*p).DATA。在您的代码中,您使用node_t typedef定义struct node类型。这意味着您可以使用node_t *引用指向struct node的指针,并且可以使用node_t->DATA访问由node_t指向的struct node的DATA成员。看起来您正在尝试实现算法的第一步,即为新节点分配内存并将ITEM值存储在节点的DATA成员中。您正在使用malloc为新节点分配内存,但是您需要初始化节点的DATA成员和LINK成员。您可以通过使用箭头操作符访问节点的成员来完成此操作:

node_t *create(int head, int item){ node_t* new = NULL; new = (node_t *)malloc(sizeof(node_t)); if(new == NULL){ printf("Memory not available"); return -1; } new->DATA = item; // Set the DATA member of the new node new->LINK = NULL; // Set the LINK member of the new node to NULL }

您还需要从create函数返回新节点,以便稍后在算法中使用它。

node_t *create(int head, int item){ node_t* new = NULL; new = (node_t *)malloc(sizeof(node_t)); if(new == NULL){ printf("Memory not available"); return -1; } new->DATA = item; // Set the DATA member of the new node new->LINK = NULL; // Set the LINK member of the new node to NULL return new; // Return the new node }

然后,你可以使用create函数创建一个新节点,并将其存储在主程序的一个局部变量中,这样你就可以继续实现算法的其余部分。

int main() { int head = 0; // The head of the linked list int item = 5; // The data to store in the new node node_t *new_node = create(head, item); // Create a new node // Continue implementing the rest of the algorithm... return 0; }


【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3