0% found this document useful (0 votes)
16 views3 pages

Programa Aula

Uploaded by

brumag
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
16 views3 pages

Programa Aula

Uploaded by

brumag
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 3

#include<stdio.

h>
#include <stdlib.h>

typedef int t_data;


typedef struct node{
t_data data;
struct node *next;
} t_node;
t_node *newNode(t_data data){
t_node *node;
node = (t_node *) malloc(sizeof(t_node));
if(node == NULL){
printf("Insuficient memory. Exiting.");
system("pause");
exit(0);
}
node->data = data;
node->next = NULL;

return node;
}
void printList(t_node *list){
if(list == NULL){
printf("Empty list.\n");
return;
}
do{
printf("%d", list->data);
list = list->next;

if(list != NULL) printf(" -> ");


} while(list != NULL);
printf("\n");
}
void headInsert(t_node **list, t_node *node){
node->next = *list;
*list = node;
}
t_node *headRemove(t_node **list){
t_node *node;
if(*list == NULL){
printf("Error removing. Empty list.\n");
return NULL;
}
node = *list;
*list = (*list)->next;

return node;
}
void tailInsert(t_node **list, t_node *node){
t_node *last = *list;

if(*list == NULL){
*list = node;
return;
}
while(last->next != NULL)
last = last->next;

last->next = node;
}
t_node *tailRemove(t_node **list){
t_node *beforeLast = *list;
t_node *node;
if(*list == NULL){
printf("Error removing. Empty list.\n");
return NULL;
}
if((*list)->next == NULL){
node = *list;
*list = NULL;
return node;
}
while(beforeLast->next->next != NULL)
beforeLast = beforeLast->next;
node = beforeLast->next;
beforeLast->next = NULL;
return node;
}
void sortInsert(t_node **list, t_node *node){
if(*list == NULL || (*list)->data >= node->data)
headInsert(list, node);
else
sortInsert(&((*list)->next), node);
}
t_node *removeByVal(t_node **list, t_data val){
t_node *node;

if(*list == NULL)
return NULL;
if((*list)->data == val){
node = headRemove(list);
return node;
}
removeByVal(&((*list)->next), val);
}
int main(void){
t_node *theList = NULL;
t_node *node;
t_data val=0;
int *p = NULL;
int op;
do{
printf("1: Inserir\n");
printf("2: Remover\n");
printf("0: Sair\n");
scanf("%d", &op);
switch(op){
case 1:
printf("Elemento a introduzir na lista: ");
scanf("%d", &val);
node = newNode(val);
sortInsert(&theList, node);
break;
case 2:
printf("Elemento a remover da lista: ");
scanf("%d", &val);
removeByVal(&theList, val);
break;
case 0: break;
default: printf("Opcao invalida.\n");
}
printList(theList);
} while(op != 0);
}

You might also like