RainyVengeance
RainyVengeance

Reputation: 3

How would I make a copy of a linked list using an ADT in C?

So I am given the following structs:

typedef struct nodeStruct
{
    int data;
    struct nodeStruct *next;
}Node;

typedef struct linkedList
{
    Node *head, *tail;
}List;

I have to make to create a function that copies the contents of an existing list into a new one using the given function prototype:

List *copyList(List *passedList);

How would I go about doing this? It is stomping me.

Edit: If it helps, I have this function to create a null list:

List *createList()
{
    List *newList = (List *)malloc(sizeof(List));

    if (newList == NULL)
    {
        puts("ERROR: Could not allocate memory\n");
        return NULL;
    }

    newList->head = newList->tail = NULL;
    return newList;
}

Edit x2: I have a createNode function and an insertAtTail (append) function as follows:

Node *createNode(int nodeValue) // this function creates a node with the value that is passed to it
{
    Node* newNode = (Node*)malloc(sizeof(Node));
    newNode -> data = nodeValue;
    newNode -> next = NULL;
    return newNode;
}

int insertAtTail(int nodeValue, List *passedList)
{
    Node *newNode = (Node *)malloc(sizeof(Node));

    if (newNode == NULL)
    {
        puts("ERROR: Could not allocate memory.\n");
        return -1;
    }

    newNode -> data = nodeValue;
    newNode -> next = NULL;

    if (passedList->tail == NULL)
    {
        passedList->head = passedList->tail = newNode;
    }
    else
    {
        passedList->tail->next = newNode;
        passedList->tail = newNode;
    }
    return 1;
}

Thanks in advance!

Upvotes: 0

Views: 186

Answers (1)

David G
David G

Reputation: 96845

You can break this down into tasks:

  1. Create a new node.
  2. Iterate through old list.
  3. Add node to the new list.

So make a function called createNode() which returns to the caller a new node just like createList() does.

Then make a function called appendList() (or whatever name you like) which adds a single node to the end of a linked list. This function should use createNode() to make the new node. It should also be able to handle adding a node to an empty linked list as well.

Then inside copyList(), create a new list (the one you will be copying values into), iterate over the old linked list and call your appendList() function to put the node value into the new list. Then return a pointer to the new list.

Upvotes: 1

Related Questions