Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <stdint.h>
- #include <string.h>
- #include <stdlib.h>
- #define NMAX 1001
- void checkAlloc(const void *const p) {
- if (p == NULL) {
- perror("");
- exit(EXIT_FAILURE);
- }
- }
- typedef struct Node {
- char text[NMAX];
- struct Node *prev, *next;
- } Node;
- Node *newNode(const char s[NMAX]) {
- Node *node = malloc(sizeof(Node));
- checkAlloc(node);
- node->next = node->prev = NULL;
- strcpy(node->text, s);
- return node;
- }
- typedef struct {
- Node *first, *last;
- } List;
- void initList(List *list) {
- list->first = list->last = NULL;
- }
- void printList(const List *const list) {
- for (Node *it = list->first; it; it = it->next) {
- fputs(it->text, stdout);
- }
- fputc('\n', stdout);
- }
- void freeList(List *list) {
- Node *next;
- for (Node *it = list->first; it; it = next) {
- next = it->next;
- free(it);
- }
- }
- void addOrd(List *list, const char text[NMAX]) {
- Node *node = newNode(text);
- Node *prev = NULL, *curr = list->first;
- while (curr != NULL && strcmp(curr->text, text) < 0) {
- prev = curr;
- curr = curr->next;
- }
- if (prev == NULL) {//to start
- node->next = list->first;
- list->first = node;
- } else {
- prev->next = node;
- node->next = curr;
- }
- }
- int main(int argc, char *argv[]) {
- if (argc == 1) {
- fprintf(stderr, "arg error!\n");
- exit(-1);
- }
- List list;
- initList(&list);
- FILE *file = fopen(argv[1], "r");
- if (file == NULL) {
- perror("");
- freeList(&list);
- exit(EXIT_FAILURE);
- }
- static char line[NMAX];
- while (fgets(line, NMAX, file)) {
- addOrd(&list, line);
- }
- printList(&list);
- freeList(&list);
- if (fclose(file) == EOF) {
- perror("");
- }
- return EXIT_SUCCESS;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement