rendered paste body/* *
* Exercicio para Estruturas de Dados I.
* Lista Simplismente Encadeada.
*
* Fabio Galdino
* Maiko Min Ian Lie
* */
#include <iostream>
#include <cstdlib>
struct node {
int value;
struct node *next;
};
void addNodeBeg(struct node **head);
void addNodeEnd(struct node **head);
void removeNodeBeg(struct node **head);
void removeNodeEnd(struct node **head);
void printList(struct node *head);
void menu(struct node **head);
void menu(struct node **head)
{
int option;
std::cout << "\n1. Inclusao no inicio da lista.\n"
<< "2. Inclusao no fim da lista.\n"
<< "3. Remocao do inicio da lista.\n"
<< "4. Remocao do fim da lista.\n"
<< "5. Impressao da lista.\n"
<< "6. Sair.\n\n";
std::cin >> option;
switch (option) {
case 1:
addNodeBeg(head);
break;
case 2:
addNodeEnd(head);
break;
case 3:
removeNodeBeg(head);
break;
case 4:
removeNodeEnd(head);
break;
case 5:
printList(*head);
break;
case 6:
exit(0);
break;
default:
std::cout << "Opcao invalida." << std::endl;
break;
}
}
void addNodeBeg(struct node **head)
{
struct node *newNode;
if (*head == NULL) {
newNode = new node;
newNode->next = NULL;
*head = newNode;
} else {
newNode = new node;
newNode->next = *head;
*head = newNode;
}
std::cout << "Digite o valor para o novo nodo:" << std::endl;
std::cin >> newNode->value;
}
void addNodeEnd(struct node **head)
{
struct node *newNode;
struct node *tempNode;
if (*head == NULL) {
newNode = new node;
newNode->next = NULL;
*head = newNode;
} else {
newNode = new node;
tempNode = *head;
while (tempNode->next != NULL) {
tempNode = tempNode->next;
}
tempNode->next = newNode;
newNode->next = NULL;
}
std::cout << "Digite o valor para o novo nodo:" << std::endl;
std::cin >> newNode->value;
}
void removeNodeBeg(struct node **head)
{
struct node *tempNode;
if (*head == NULL) {
std::cout << "Lista vazia." << std::endl;
return;
}
if ((*head)->next == NULL) {
free(*head);
*head = NULL;
return;
}
tempNode = *head;
*head = (*head)->next;
free(tempNode);
}
void removeNodeEnd(struct node **head)
{
struct node *tempNode;
if (*head == NULL) {
std::cout << "Lista vazia." << std::endl;
return;
}
if ((*head)->next == NULL) {
free(*head);
*head = NULL;
return;
}
tempNode = *head;
while ((tempNode->next)->next != NULL) {
tempNode = tempNode->next;
}
free(tempNode->next);
tempNode->next = NULL;
}
void printList(struct node *head)
{
int i;
struct node *tempNode;
if (head == NULL) {
std::cout << "Lista vazia." << std::endl;
return;
}
i = 0;
tempNode = head;
while (tempNode->next != NULL) {
std::cout << '[' << i << ']' << " Value: " << tempNode->value;
std::cout << " Address: " << tempNode << std::endl;
tempNode = tempNode->next;
i++;
}
std::cout << '[' << i << ']' << " Value: " << tempNode->value;
std::cout << " Address: " << tempNode << std::endl;
}
int main(void)
{
struct node *head;
head = NULL;
while (true) {
menu(&head);
}
return 0;
}