DropsBrowse Pastes
Login with GitHub

链表 with tail

November 30th, 2021Views: 13(0 unique)C
#include <stdio.h>
#include <stdlib.h>

typedef struct node
{
    int number;
    struct node *next;
} node;

node *list = NULL;
node *tail = NULL;

void freeList(node *list);
void insertNode(void);
void sortList(void);
void printList(void);

int main(void)
{
    while(1)
    {
        insertNode();
        sortList();
        printList();
    }

    freeList(list);

    return 0;
}

void freeList(node *list)
{
    while (list != NULL)
    {
        node *t = list->next;
        free(list);
        list = t;
    }

    return;
}

void insertNode(void)
{
    node *currentNode = malloc(sizeof(node));
    if (currentNode == NULL)
    {
        freeList(list);
        exit(1);
    }

    printf("Please enter a number: ");
    scanf("%d", &(currentNode->number));
    currentNode->next = NULL;

    if (tail == NULL)
    {
        list = currentNode;
        tail = currentNode;
    }
    else
    {
        tail->next = currentNode;
        tail = currentNode;
    }

    return;
}

void sortList(void)
{
    for (node *t = list; t->next != NULL; t = t->next)
    {
        for (node *u = list; u->next != NULL; u = u->next)
        {
            if (u->number > u->next->number)
            {
                int v = u->number;
                u->number = u->next->number;
                u->next->number = v;
            }
        }
    }

    return;
}

void printList(void)
{
    for (node *t = list; t != NULL; t = t->next)
    {
        printf("%d ", t->number);
    }
    putchar('\n');

    return;
}