C++ Programming GalleryThe Programming Challenge

Challenge 4 – What are the three main errors in the program? in C++

Difficulty x10
x5

This Challenge was proposed for the now defunct C/C++ programming list CWORLD in 1999.
The source code of the challenge has been updated to modern C++, but maintaining the essence of the challenge, which its original author wanted to transmit.

Date: 28-VIII-2000
Created by: David A. Capello
Challenge winner: Antonio Romeral

Here’s something not so difficult, pay close attention.

What are the three main errors in the program?

The final result of the program should look like the initial image of this post.

Source Code

/*
* Here's something not so difficult, pay close attention.
* What are the three main errors in the program?
*/

#include <iostream>

typedef struct ELEMENTO
{
	int a, b, c;
	struct ELEMENTO *proximo;
} ELEMENTO;



typedef struct LISTA
{
	ELEMENTO *primero;
	int elementos;
} LISTA;



ELEMENTO *agregar_elemento_al_final(LISTA *lista, int a, int b, int c)
{
	ELEMENTO *nuevo, *posicion, *anterior=NULL;

	posicion = lista->primero;
	while (posicion) {
		anterior = posicion;
		posicion = posicion->proximo;
	}

	nuevo = new ELEMENTO;
	if (!nuevo)
		return NULL;

	nuevo->a = a;
	nuevo->b = b;
	nuevo->c = c;
	nuevo->proximo = NULL;

	if (!posicion)
		lista->primero = nuevo;
	else
		anterior->proximo = nuevo;

	lista->elementos++;

	return nuevo;
}



void borrar_elemento(LISTA *lista, ELEMENTO *elemento)
{
	ELEMENTO *posicion = lista->primero, *anterior = NULL;

	while (posicion) {
		if (posicion == elemento) {
			anterior->proximo = posicion->proximo;
			delete elemento;
			lista->elementos--;
			break;
		}
		anterior = posicion;
		posicion = posicion->proximo;
	}
}



LISTA *crear_lista(void)
{
	LISTA *lista;

	lista = new LISTA;
	if (!lista)
		return NULL;

	lista->primero = NULL;
	lista->elementos = 0;

	return lista;
}



void borrar_lista(LISTA *lista)
{
	ELEMENTO *posicion = lista->primero;

	while (posicion) {
		delete posicion;
		posicion = posicion->proximo;
	}

	delete lista;
}



void imprimir_lista(LISTA *lista)
{
	ELEMENTO *posicion = lista->primero;

	while (posicion) {
		std::cout << "a="<< posicion->a << " b=" << posicion->b << " c=" << posicion->c << std::endl;
		posicion = posicion->proximo;
	}
}



int main(void)
{
	LISTA *lista = crear_lista();
	ELEMENTO *elemento;

	std::cout << "--\n";

	elemento =
		agregar_elemento_al_final(lista, 20, 1, -5);
	agregar_elemento_al_final(lista, 10, 2, -6);
	agregar_elemento_al_final(lista, 0, 3, -7);
	agregar_elemento_al_final(lista, 1, 3, -7);

	borrar_elemento(lista, elemento);

	imprimir_lista(lista);
	borrar_lista(lista);
	return 0;
}

AND FINALLY I CAN ONLY SAY …. BEST OF LUCK AND MAY THE BEST CODE WIN….

If you liked this challenge remember to leave a comment in our guestbook

Solution

Leave a Reply

Your email address will not be published. Required fields are marked *

Back to top button