如何修改添加到列表的末尾

时间:2020-01-17 19:52:16

标签: c99

我正在使用列表,但我不明白如何修改代码以将字符添加到列表的末尾,现在有了此代码,我将它们添加到列表的顶部。

#include <stdio.h>
#include <stdlib.h>
#define MAX 10

typedef struct node{
    char character;
    struct node *next;
} node_t;

node_t *createNode(char ch){
    node_t *result = malloc(sizeof(node_t));
    result->character = ch;
    result->next = NULL;
    return result;
}

int main (){

    node_t *head=NULL, *temp;
    int i;
    char ch;

    for (i=0; i < MAX; i++){
        printf("Write a character: \n");
        scanf(" ");
        scanf("%c", &ch);
        temp = createNode(ch);
        temp->next = head;
        head = temp;
    }

    while (temp != NULL) {
        printf("%c ", temp->character);
        temp = temp->next;
    }

    printf ("\n"); 

    return 0;
}

0 个答案:

没有答案