gpt4 book ai didi

使用一个函数创建两个链表

转载 作者:行者123 更新时间:2023-11-30 17:13:07 25 4
gpt4 key购买 nike

我有一个名为 ll() 的函数,用于创建链接列表,如下所示。我的程序需要两个链表。是否可以重用此函数,以便我可以有两个链接列表,例如 head1 和 head2?

#include <stdio.h>
#include <malloc.h>

typedef struct node
{
int data;
struct node* link;
} Node;

Node* head = NULL;
Node* previous = NULL;

int main(void)
{
ll();

print();

return 0;
}

int ll()
{
int data = 0;
while(1)
{
printf("Enter data, -1 to stop: ");
scanf("%d", &data);

if(data == -1)
break;

addtoll(data);
}
}

int addtoll(int data)
{
Node* ptr = NULL;

ptr = (Node*)malloc(sizeof(Node));
ptr->data = data;
ptr->link = NULL;

if(head == NULL)
head = ptr;
else
previous->link = ptr;

previous = ptr;
}

int print()
{
printf("Printing linked list contents: ");
Node* ptr = head;

while(ptr)
{
printf("%d ", ptr->data);
ptr = ptr->link;
}
printf("\n");
}

有没有比这样做更好的方法

main()
{
ll(1);
ll(2);
}

int ll(int serial)
{
if (serial == 1)
Use head1 everywhere in this function
else if(serial == 2)
Use head2 everywhere in this function
}

最佳答案

除了传递 int 之外,您还可以只传递链表。

Node head1;
Node head2;
Node previous1;
Node previous2;

int main(){
ll(&head1, &previous1);
ll(&head2, &previous2);
}

int ll(Node* head, Node* previous)
{
int data = 0;
scanf("%d",&data);
*head = {data, null};
previous = head;

while(1)
{
printf("Enter data, -1 to stop : ");
scanf("%d",&data);

if(data == -1)
break;

addtoll(data, previous);
}
}

int addtoll(int data, Node* previous)
{
struct student newNode = {data, null}
previous->link = &newNode;
previous = &newNode;
}

关于使用一个函数创建两个链表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31035570/

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