Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // queue2.cpp : Этот файл содержит функцию "main". Здесь начинается и заканчивается выполнение программы.
- // Удалить любой элемент из однонаправленной очереди
- #include "pch.h"
- #include <stdio.h>
- #include <stdlib.h>
- #include <string.h>
- struct queue
- {
- char* str;
- struct queue* next;
- };
- void add_elemenet(struct queue** head, struct queue** tail, char* str)
- {
- struct queue* temp = (struct queue*)malloc(sizeof(struct queue));
- temp->str = (char*)malloc(sizeof(char) * (strlen(str) + 1));
- strcpy(temp->str, str);
- temp->next = NULL;
- if (*head == NULL)
- {
- *head = *tail = temp;
- return;
- }
- temp->next = *tail;
- *tail = temp;
- }
- void show_queue(struct queue* tail)
- {
- if (!tail)
- {
- return;
- }
- do
- {
- puts(tail->str);
- tail = tail->next;
- } while (tail);
- fprintf(stdout, "\n\n");
- }
- void dequeue(struct queue** head, struct queue** tail) //first element remove
- {
- if (!*head)
- {
- return;
- }
- if (*head == *tail)
- {
- free((*head)->str);
- free(*head);
- *head = *tail = NULL;
- return;
- }
- struct queue* temp = *tail;
- while (temp->next != *head)
- {
- temp = temp->next;
- }
- *head = temp;
- free(temp->next->str);
- free(temp->next);
- temp->next = NULL;
- }
- void remove_any(struct queue** head, struct queue** tail, char* str)
- {
- if (!head)
- {
- return;
- }
- if (*tail == *head)
- {
- if (strcmp((*head)->str, str) == 0)
- {
- free((*head)->str);
- free(*head);
- *head = *tail = NULL;
- }
- return;
- }
- struct queue* cur = *tail;
- struct queue* prev;
- while (*tail && strcmp(cur->str, str) == 0)
- {
- *tail = (*tail)->next;
- free(cur->str);
- free(cur);
- cur = *tail;
- }
- cur = (*tail)->next;
- prev = *tail;
- while (cur)
- {
- if (strcmp(cur->str, str) == 0)
- {
- if (cur == *head)
- {
- *head = prev;
- (*head)->next = NULL;
- free(cur->str);
- free(cur);
- return;
- }
- prev->next = cur->next;
- free(cur->str);
- free(cur);
- cur = prev->next;
- }
- else
- {
- prev = cur;
- cur = cur->next;
- }
- }
- }
- int main()
- {
- struct queue* head = NULL, *tail = NULL;
- char* str = NULL;
- for(;;)
- {
- str = (char*)malloc(sizeof(char) * 100);
- gets_s(str, 100);
- if (str[0] == '\0' )
- {
- free(str);
- break;
- }
- add_elemenet(&head, &tail, str);
- free(str);
- }
- show_queue(tail);
- dequeue(&head, &tail);
- show_queue(tail);
- str = (char*)malloc(sizeof(char) * 100);
- gets_s(str, 100);
- remove_any(&head, &tail, str);
- show_queue(tail);
- free(str);
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement