benhi
benhi

Reputation: 582

How to add and print items in Linked List c

My main is:

void main()
{
    int flag = 1;
    LinkedList *list = NULL;
    list = makeList();
    while (flag) {
        add_last(list, makeNode(nextKey(), "uninitialized"));
        printf("please enter 0 to stop any other number to go on \n");
        scanf("%d",&flag);
    }
    printKeys(list);
}

I have 2 structs that define node and list:

typedef struct item{
    int data;
    char *charData;
    struct item *next;
}item;

typedef struct{
    struct item *head;
}LinkedList;

I create the list by the function:

LinkedList *makeList(){
    LinkedList *head = (LinkedList*)malloc(sizeof(LinkedList));
    return head;
}

and the node by the function:

item *makeNode(int key, char* data){
    item *newItem = (item*)malloc(sizeof(item));
    if (newItem != NULL) {
        newItem->data = key;
        newItem->next = NULL;
    }
    return newItem;
}

Now I need to write 2 functions, 1 to add the new item in the end of the list, and the second to Print the list.

The signing my first function is:

void add_last(LinkedList *list, item *newItem){

}

and the second is:

void printKeys(LinkedList *list){

}

I am novice in the world of "C" and I don't know how can I do this. I don't understand how to have access to the list.

Thank...

Upvotes: 2

Views: 2262

Answers (2)

benhi
benhi

Reputation: 582

void add_last(LinkedList *list, item *newItem){

    item* ptrTemp = list->head;

    if (list!=NULL) {
        if (list->head == NULL) {
            list->head = newItem;
            return;
        }
        while (ptrTemp->next != NULL) {
            ptrTemp = ptrTemp->next;
        }
        ptrTemp->next = newItem;
    }
}

void printKeys(LinkedList *list){

    item* ptrTemp = list->head;
    while (ptrTemp->next != NULL) {
        printf("%d",ptrTemp->data);
        ptrTemp = ptrTemp->next;
    }
    printf("%d\n",ptrTemp->data);
}

Upvotes: 0

Codor
Codor

Reputation: 17605

The printKeys function should iterate over the nodes until one node is found where next is null. By doing so, the key field should be printed. The add_last function should perhaps iterate until the last node is found, and then set the next field of the last node to newItem.

Upvotes: 2

Related Questions