@nait123321

Как превратить очередь в 2 очереди?

Здравствуйте, мне нужно для лабы сделать следующие: очередь превратить в 2 очереди( в 1 - парные числа, во 2 - не парные). 5 элемент каждой очереди должен быть удалён.
Я написал так:
#include <stdlib.h>
#include <stdio.h>
#include <locale.h>
int A=0;
int B=0;
struct TNode {
	int data; // Інформаційний блок
	struct TNode *next; // Адресний блок
};
typedef struct TNode Node;
void push(Node **head, Node **tail, int data)
{
	Node *NewNode = (Node*)malloc(sizeof(Node)); // Покажчик на новий елемент
	NewNode->data = data; // Інформація
	NewNode->next = NULL; // NULL вказує на те, що цей елемент останній
		if ((*head) == NULL)//Якщо черга порожня
		{
			(*head) = (*tail) = NewNode;// Покажчики на голову та кінець черги вказують на 1 елемент
		}
		else//Якщо черга не порожня
		{
			(*tail)->next = NewNode;
			(*tail) = NewNode;
		}
}
void Duble(Node **head, Node **tail, Node **headp, Node **headnp, Node **tailp, Node **tailnp)
{
	Node *NewNode = (Node*)malloc(sizeof(Node)); // Покажчик на новий елемент
	NewNode->data = (*head)->data; // Інформація
	NewNode->next = NULL; // NULL вказує на те, що цей елемент останній
	if ((*head) == NULL)//Якщо черга порожня
	{
		(*head) = (*tail) = NewNode;// Покажчики на голову та кінець черги вказують на 1 елемент
	}
	if ((*head)->data % 2 == 0)
	{
		if(A!=4)
		{
			(*tailp)->next = NewNode;
			(*tailp) = NewNode;
		}
		++A;
	}
	else//Якщо черга не порожня
	{
		if (B != 4)
		{
			(*tailnp)->next = NewNode;
			(*tailnp) = NewNode;
		}
		++B;
	}
}
void print(Node* head)//Функція для виводу черги на екран
{
	printf("\nЧерга\n");
	while (head) // Виведення результатів
	{
		printf("%d\n", head->data);
		head = head->next;
	}
}
int main()
{
	setlocale(LC_ALL, "ukr");
	Node *head = NULL; // Покажчик, який вказує на голову черги
	Node *tail = NULL; // Покажчик, який вказує на хвіст черги
	Node *headp = NULL; // парне
	Node *tailp = NULL;
	Node *headnp = NULL; // непарне
	Node *tailnp = NULL;
	int a, b;
	for (int i = 0; i < 20; i++) // Цикл для створення 5 вузлів
	{
		push(&head, &tail, i + 1); // Функція створення вузла
	}
	print(head);//Виведення черги на екран
	Duble(&head, &tail, &headp, &headnp, &tail, &tailnp);
	print(headp);
	print(headnp);
	_getch();
	return 1;
}

При запуске выбивает ошибку.
Exception thrown at 0x00D45137 in Laba6.exe: 0xC0000005: Access violation writing location 0x00000004.

If there is a handler for this exception, the program may be safely continued

Где ошибка?
  • Вопрос задан
  • 405 просмотров
Решения вопроса 1
Не разобрался, в чем проблема, вот рабочее решение:
spoiler
#include <stdlib.h>
#include <stdio.h>

struct TNode {
	int data;
	struct TNode *next;
};
typedef struct TNode Node;

struct TQueue {
	Node* head;
	Node* tail;
};
typedef struct TQueue Queue;

Queue* newQueue()
{
	Queue* queue = malloc(sizeof(Queue));
	queue->head = NULL;
	queue->tail = NULL;
	return queue;
}

void deleteQueue(Queue* queue)
{
	Node* current = queue->head;
	while (current != NULL) {
		Node* next = current->next;
		free(current);
		current = next;
	}
	free(queue);
}

void pushBackQueue(Queue* queue, int data)
{
	Node* newNode = malloc(sizeof(Node));
	newNode->data = data;
	newNode->next = NULL;

	if (queue->tail == NULL) {
		queue->head = newNode;
		queue->tail = newNode;
	}
	else {
		queue->tail->next = newNode;
		queue->tail = newNode;
	}
}

void splitQueue(Queue* source, Queue* even, Queue* odd)
{
	for (Node* current = source->head; current != NULL; current = current->next) {
		int data = current->data;
		pushBackQueue((data % 2 == 0) ? even : odd, data);
	}
}

void printQueue(Queue* queue)
{
	for (Node* current = queue->head; current != NULL; current = current->next) {
		printf("%d ", current->data);
	}
	printf("\n");
}

int main()
{
	Queue* source = newQueue();
	for (int i = 0; i < 20; i++) {
		pushBackQueue(source, i + 1);
	}
	printQueue(source);

	Queue* even = newQueue();
	Queue* odd = newQueue();
	splitQueue(source, even, odd);
	printQueue(even);
	printQueue(odd);

	deleteQueue(source);
	deleteQueue(even);
	deleteQueue(odd);

	system("pause");  // not needed in Linux
	return 1;
}


И лучше убрать C++ из заголовка, иначе возникают вопросы типа "почему без классов" и "почему не std::linked_list".
Ответ написан
Пригласить эксперта
Ответы на вопрос 1
@nait123321 Автор вопроса
Изменил код, ошибок уже нету, но остольные 2 списка не заполняются
#include <stdlib.h>
#include <stdio.h>
#include <locale.h>
int A=0;
int B=0;
struct TNode {
	int data; // Інформаційний блок
	struct TNode *next; // Адресний блок
};
typedef struct TNode Node;
typedef struct TNode NodeP;
typedef struct TNode NodeNP;
void push(Node **head, Node **tail, int data)
{
	Node *NewNode = (Node*)malloc(sizeof(Node)); // Покажчик на новий елемент
	NodeP *NewNodeP = (NodeP*)malloc(sizeof(NodeP));
	NodeNP *NewNodeNP = (NodeP*)malloc(sizeof(NodeNP));
	NewNode->data = data; // Інформація
	if (data % 2 == 0)
	{
		if (A != 4)
		{
			NewNodeP->data= NewNode->data;
		}
		++A;
	}
	else
	{
		if (B != 4)
		{
			NewNodeNP->data=data;
		}
		++B;
	}
	NewNode->next = NULL; // NULL вказує на те, що цей елемент останній
		if ((*head) == NULL)//Якщо черга порожня
		{
			(*head) = (*tail) = NewNode;// Покажчики на голову та кінець черги вказують на 1 елемент
		}
		else//Якщо черга не порожня
		{
			(*tail)->next = NewNode;
			(*tail) = NewNode;
		}

}
void print(Node* head)//Функція для виводу черги на екран
{
	printf("\nЧерга\n");
	while (head) // Виведення результатів
	{
		printf("%d\n", head->data);
		head = head->next;
	}
}
void printp(NodeP* headp)//Функція для виводу черги на екран
{
	printf("\nЧерга\n");
	while (headp) // Виведення результатів
	{
		printf("%d\n", headp->data);
		headp = headp->next;
	}
}
int main()
{
	setlocale(LC_ALL, "ukr");
	Node *head = NULL; // Покажчик, який вказує на голову черги
	Node *tail = NULL; // Покажчик, який вказує на хвіст черги
	NodeP *headp = NULL; // парне
	NodeP *tailp = NULL;
	NodeNP *headnp = NULL; // непарне
	NodeNP *tailnp = NULL;
	int a, b;
	for (int i = 0; i < 20; i++) // Цикл для створення 5 вузлів
	{
		push(&head, &tail, i + 1); // Функція створення вузла
	}
	print(head);//Виведення черги на екран
	headp->data = head->data;
	printp(headp);
	print(headnp);
	_getch();
	return 1;
}
Ответ написан
Комментировать
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы