Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <stdlib.h>
- typedef struct Pair
- {
- int value;
- int times;
- } Pair;
- typedef struct Node
- {
- Pair pair;
- struct Node *prev;
- struct Node *next;
- } Node;
- void print_pair(Node *ptr) {
- if (ptr == NULL) {
- printf("%s", "NULL");
- } else {
- printf("%d %d", ptr->pair.value, ptr->pair.times);
- }
- // printf("");
- }
- void add_in_start(Node **head_ref, Node **tail_ref, Pair value) {
- Node *new_node = malloc(sizeof(Node));
- new_node->pair = value;
- new_node->next = *head_ref;
- new_node->prev = NULL;
- if (*head_ref != NULL) {
- (*head_ref)->prev = new_node;
- } else { // head_ref == NULL <=> tail_ref == NULL
- *tail_ref = new_node;
- }
- *head_ref = new_node;
- }
- void remove_node(Node **head_ref, Node **tail_ref, Node *node_ref) {
- if (node_ref->prev != NULL) {
- node_ref->prev->next = node_ref->next;
- } else {
- *head_ref = node_ref->next;
- }
- if (node_ref->next != NULL) {
- node_ref->next->prev = node_ref->prev;
- } else {
- *tail_ref = node_ref->prev;
- }
- free(node_ref);
- }
- void add(Node **head_ref, Node **tail_ref, int number) {
- Node *ptr = *head_ref;
- while (ptr != NULL) {
- if (ptr->pair.value == number) {
- Pair new_pair = (Pair) { ptr->pair.value, ptr->pair.times + 1 };
- remove_node(head_ref, tail_ref, ptr);
- add_in_start(head_ref, tail_ref, new_pair);
- return;
- }
- ptr = ptr->next;
- }
- add_in_start(head_ref, tail_ref, (Pair) { number, 1 });
- }
- void print_from_head(Node **head_ref) {
- Node *ptr = *head_ref;
- while (ptr != NULL) {
- print_pair(ptr->prev);
- print_pair(ptr);
- print_pair(ptr->next);
- printf("%s", "\n");
- ptr = ptr->next;
- }
- }
- void print_from_tail(Node **tail_ref) {
- Node *ptr = *tail_ref;
- while (ptr != NULL) {
- // print_pair(ptr->prev);
- print_pair(ptr);
- // print_pair(ptr->next);
- printf("%s", "\n");
- ptr = ptr->prev;
- }
- }
- void free_list(Node **head_ref) {
- Node *ptr = *head_ref;
- while (ptr != NULL) {
- Node *tmp = ptr->next;
- free(ptr);
- ptr = tmp;
- }
- }
- int main() {
- Node *head = NULL;
- Node *tail = NULL;
- int number;
- while (scanf("%d", &number) == 1) {
- add(&head, &tail, number);
- // print_from_head(&head);
- }
- /*
- add_in_start(&head, &tail, (Pair) {1, 1});
- add_in_start(&head, &tail, (Pair) {2, 1});
- add_in_start(&head, &tail, (Pair) {3, 1});
- add_in_start(&head, &tail, (Pair) {4, 1});
- remove_node(&head, &tail, head->next);
- remove_node(&head, &tail, tail->prev);
- remove_node(&head, &tail, tail);
- remove_node(&head, &tail, head);
- */
- print_from_tail(&tail);
- free_list(&head);
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement