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

标签 c data-structures linked-list

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

相关文章:

c - 多线程正在以选项卡形式写入输出

java - 存储来自 count-min-sketch 的前 k 个结果

同步 LinkedList 中的 java.util.NoSuchElementException

异或交换会导致溢出吗?它是否适用于 float ?

c - 如何使用 MPI 或 OpenMP 并行化函数调用

data-structures - 在 Big Oh Complexity 中嵌套 for 循环

C++ 链表——如何在不重复相同节点的情况下读取

c - 从链表中删除元素时出现异常

c - posix 的线程优先级

algorithm - 如何插入作为二叉树实现的二叉最大堆?