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

时间:2015-06-24 19:41:38

标签: 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
}

2 个答案:

答案 0 :(得分:1)

您也可以只传递链接列表,而不是传递一个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;
}

答案 1 :(得分:-1)