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

Create two linked lists using one function

我有一个名为 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;
}

Exceutable Code to implement more than 1 Linked List by appending new node one by one.