gpt4 book ai didi

c - 如何模块化链表?

转载 作者:行者123 更新时间:2023-11-30 16:41:35 24 4
gpt4 key购买 nike

我有以下链接列表:

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

struct Node
{
int data; // Linked List type of data.
struct Node *next; // Pointer to the next Node.
};

void printfList(struct Node *head)
{
while(head != NULL)
{
printf(" %d\n", head -> data);
head = head -> next;
}
}


int main()
{
struct Node *head = NULL;
struct Node *second = NULL;
struct Node *third = NULL;

head = (struct Node*) malloc(sizeof(struct Node));
second = (struct Node*) malloc(sizeof(struct Node));
third = (struct Node*) malloc(sizeof(struct Node));

head -> data = 1;
head -> next = second;

second -> data = 2;
second -> next = third;

third -> data = 3;
third -> next = NULL;

printfList(head);

return 0;
}

如何模块化这个示例以获得更专业的东西?节点类型并与其他节点分开并单独运行?

最佳答案

我认为这里的“模块化”意味着更专业、更干净的代码,我想出了以下内容:

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

struct Node
{
int data; // Linked List type of data.
struct Node *next; // Pointer to the next Node.
};
struct Node * makeNode(int data){
struct Node *temp = (struct Node*)malloc(sizeof(struct Node));
temp->data = data;
temp->next = NULL;
return temp;
}
void printfList(struct Node *head)
{
while(head != NULL)
{
printf(" %d\n", head -> data);
head = head -> next;
}
}


int main()
{
struct Node *head, *prev;
int i, n;
printf("How many values you want to insert ?");
scanf("%d", &n);
printf("\nNow enter values :\n");
for(i = 0; i < n; i++){
int val;
scanf("%d", &val);
if(i == 0){
head = makeNode(val);
prev = head;
}
else{
struct Node *temp = makeNode(val);
prev->next = temp;
prev = temp;
}
}

printfList(head);

return 0;
}

希望有帮助。

关于c - 如何模块化链表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46228072/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com