简体   繁体   English

如何在链接列表c中添加和打印项目

[英]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: 我有2个定义节点和列表的结构:

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. 现在,我需要编写2个函数,其中1个用于在列表末尾添加新项,第二个用于打印列表。

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. 我是“ C”领域的新手,我不知道该怎么做。 I don't understand how to have access to the list. 我不知道如何访问该列表。

Thank... 谢谢...

The printKeys function should iterate over the nodes until one node is found where next is null . printKeys函数应该在节点上进行迭代,直到找到一个节点,其中nextnull为止。 By doing so, the key field should be printed. 这样,应该打印key段。 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 . add_last函数也许应该迭代直到找到最后一个节点,然后将最后一个节点的next字段设置为newItem

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);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM