terça-feira, 27 de outubro de 2015

Exemplo de Lista dinâmica usando TAD em linguagem C.
Esta lista possibilita a inserção de valores em qualquer posição da lista


arquivo.h


typedef struct sNO{

int num;
struct sNO *prox;
}NO;

typedef NO *LISTA;

void iniciar(LISTA *l);

void inserir_ini(LISTA *l, int num);
void inserir_pos(LISTA *l, int num, int pos);
void inserir_fim(LISTA *l, int num);

int remover_ini(LISTA *l);
int remover_pos(LISTA *l, int pos);
int remover_fim(LISTA *l);

void exibir(LISTA *l);

arquivo.c


#include"ListaDim.h"
#include<stdio.h>
#include<stdlib.h>
#include<conio.h>

LISTA memoria(){
//atribui memoria
return (LISTA) malloc(sizeof(NO));
}

void iniciar(LISTA *l){

*l = NULL;
}

void inserir_fim(LISTA *l, int num){
//inserir no fim
LISTA temp = memoria();

if(temp == NULL){

puts("Não foi possivel alocar memoria!");
}

temp->num = num;
temp->prox = NULL;

if(*l != NULL){

LISTA lista = *l;
while(lista->prox != NULL){

lista = lista->prox;
}
lista->prox = temp;
} else {

*l = temp;

}
}

void inserir_pos(LISTA *l, int num, int pos){

LISTA temp = memoria();
if(temp == NULL){ //verifica se alocou memoria

puts("Não foi possivel alocar memoria!");
}

temp->num = num; //recebe o valor de num
if(*l != NULL && pos == 1){

temp->prox = *l;
*l = temp;
} else 
if(*l != NULL && pos > 1){ //se a lista não estiver vazia

LISTA lista = *l; //ponteiro recebe lista
while(pos-1 > 1 && lista->prox != NULL){ //bo
pos--;
lista = lista->prox; //iteração
}
temp->prox = lista->prox;
lista->prox = temp;

} else { //se a lista estiver vazia

temp->prox = NULL;
*l = temp;
}
}

void inserir_ini(LISTA *l, int num){
//inserir no inicio
LISTA temp = memoria();
if(temp == NULL){

puts("Não foi possivel alocar memoria!");
}

temp->num = num;

if(*l != NULL){

temp->prox = *l;
*l = temp;
} else {

temp->prox = NULL;
*l = temp;
}
}

int remover_ini(LISTA *l){
//remover do inicio
int num;

if(*l != NULL){

LISTA temp = *l;
*l = temp->prox;
num = temp->num;
free(temp);
}
return num;
}

int remover_pos(LISTA *l, int pos){
//remover posiçao

int num;
if(*l != NULL){

LISTA temp;
LISTA lista = *l;
if(pos > 1){
pos--;
while(pos > 1 ){
if(lista->prox == NULL){
puts("Posicao vazia!");
return 0;
}
lista = lista->prox;
pos--;
}

temp = lista->prox;
num = temp->num;
lista->prox = temp->prox;
free(temp);

} else if(pos == 1){

temp = *l;
num = temp->num;
*l = temp->prox;
free(temp);
}

return num;
} else {

printf("lista vazia!");
}
}

int remover_fim(LISTA *l){
//remover fim
int num;
if(*l != NULL){
  
LISTA temp = *l;
*l = temp->prox;
  num = temp->num;
free(temp);
return num; 
} else {
  
  return 0; 
}
}

void exibir(LISTA *l){
//exibir lista
if(*l != NULL){
LISTA temp = *l;
puts("Lista:");
while(temp != NULL){
printf("%d\n", temp->num);
temp = temp->prox;
}
puts("");
} else {
puts("Lista vazia!");
puts("");
}
}

Nenhum comentário:

Postar um comentário