SlideShare uma empresa Scribd logo
1 de 13
Baixar para ler offline
1 #include <stdio.h>
2 #include <stdlib.h>
3 #include <locale.h>
4 #include <conio.h>
5
6 /* DEFININDO A ESTRUTURA DE NÓ */
7 struct NO
8 {
9 int num;
10 struct NO *ant;
11 struct NO *prox;
12 };
13 typedef struct NO no;
14
15 /* VARIÁVEIS GLOBAIS */
16 int tam, x;
17
18
19 /* PROTÓTIPOS DE FUNÇÕES*/
20
21 //FUNÇÕES PARA INICIALIZAR A LISTA
22 void inicia(no *LISTA);
23
24 //FUNÇÕES PARA CRIAR O MENU DO PROGRAMA
25 int menuPrincipal(void);
26 int menuAtualizar(void);
27 int menuBasico(void);
28 int menuRemover(void);
29 int menuInserir(void);
30 int menuPesquisar(void);
31
32 //FUNÇÕES PARA ESCOLHA DA OPÇÃO
33 void opcaoPrincipal(no *LISTA, int op);
34 void opcaoAtualizar(no *LISTA, int op);
35 void opcaoBasico(no *LISTA, int op);
36 void opcaoRemover(no *LISTA, int op);
37 void opcaoInserir(no *LISTA, int op);
38 void opcaoPesquisar(no *LISTA, int op);
39
40 //FUNÇÕES PARA INSERIR NA LISTA
41 no *insereFim(no *LISTA);
42 no *insereInicio(no *LISTA);
43 void insereEmOrdemCrescente(no *LISTA);
44 void insereEmOrdemDecrescente(no *LISTA);
45 void insereAnterior(no *LISTA);
46 void inserePosterior(no *LISTA);
47
48 //FUNÇÕES PARA IMPRIMIR A LISTA
49 void imprimirAnterior(no *LISTA);
50 void imprimirPosterior(no *LISTA);
51
52 //FUNÇÕES PARA LIBERAR A LISTA
53 void libera(no *LISTA);
54
55 //FUNÇÕES PARA REMOVER DA LISTA
56 no *removeInicio(no *LISTA);
57 no *removeFim(no *LISTA);
58 void removeEmOrdem(no *LISTA);
59 void removerAny(no *LISTA);
60 void removeAnterior(no *LISTA);
61 void removePosterior(no *LISTA);
62
63 //FUNÇÕES PARA PESQUISAR NÓS
64 no *buscar(no *LISTA);
65 int pesquisaMaior(no *LISTA);
66 int pesquisaMenor(no *LISTA);
67 void noAnterior(no *LISTA);
68 void noPosterior(no *LISTA);
69
70 //FUNÇÕES PARA ATUALIZAR O VALOR DE UM NÓ
71 void atualizar(no *LISTA);
72 void atualizarAnterior(no *LISTA);
73 void atualizarPosterior(no *LISTA);
74
75 //OUTRAS FUNÇÕES
76 no *inicio(no *LISTA);
77 no *fim(no *LISTA);
78 no *unico(no *LISTA);
79
80 /* PROGRAMA PRINCIPAL */
81 int main(void)
82 {
83 setlocale(LC_ALL, "Portuguese");
84 no *LISTA = (no *) malloc(sizeof(no));
85 if(!LISTA)
86 {
87 printf("nSem memória disponível!n");
88 exit(1);
89 }
90 else
91 {
92 inicia(LISTA);
93 int opt;
94
95 do
96 {
97 system("cls");
98 opt = menuPrincipal();
99 opcaoPrincipal(LISTA, opt);
100 }
101 while(opt);
102 free(LISTA);
103 return 0;
104 }
105 }
106
107 /* IMPLEMENTAÇÃO DAS FUNÇÕES */
108
109 //FUNÇÃO PARA INICIALIZAR A LISTA
110 void inicia(no *LISTA)
111 {
112 //LISTA->num = 0;
113 LISTA->ant = NULL;
114 LISTA->prox = NULL;
115 tam = 0;
116 }
117
118 //FUNÇÃO PARA CRIAR O MENU PRINCIPAL
119 int menuPrincipal(void)
120 {
121 system("cls");
122 int op;
123 printf("n|================================================================|n");
124 printf("n| MENU PRINCIPAL |");
125 printf("n| 0. SAIR DO PROGRAMA. |");
126 printf("n| 1. Funções Básicas. |");
127 printf("n| 2. Funções para Inserir nós na L.D.E. |");
128 printf("n| 3. Funções para Excluir nós da L.E.E. |");
129 printf("n| 4. Funções para Pesquisar nós da L.D.E. |");
130 printf("n| 5. Funções para Atualizar nós da L.D.E. |");
131 printf("n|Digite a opção desejada: t");
132 scanf("%d%*c", &op);
133 return op;
134 }
135
136 //FUNÇÃO PARA CRIAR O MENU DE FUNÇÕES BÁSICAS
137 int menuBasico(void)
138 {
139 system("cls");
140 int op;
141 printf("nn|================================================================|n");
142 printf("n| MENU FUNÇÕES BÁSICAS |n");
143 printf("n| 0. Sair. |n");
144 printf("n| 1. Zerar lista. |n");
145 printf("n| 2. Quantidade de NÓS da lista. |n");
146 printf("n| 3. Imprimir pelo ponteiro anterior. |n");
147 printf("n| 4. Imprimir pelo ponteiro posterior. |n");
148 printf("n| 5. Obter o nó do inicio da Lista. |n");
149 printf("n| 6. Obter o nó do fim da Lista. |n");
150 printf("n| 7. Verificar se o NÓ é o único da Lista. |n");
151 printf("n|Digite a opção desejada: t");
152 scanf("%d%*c", &op);
153 return op;
154 }
155
156 //FUNÇÃO PARA CRIAR O MENU DE FUNÇÕES PARA INSERÇÃO
157 int menuInserir(void)
158 {
159 system("cls");
160 int op;
161 printf("n|----------------------------------------------------------------|n");
162 printf("n| MENU FUNÇÕES INSERÇÃO |n");
163 printf("n| 0. Sair. |n");
164 printf("n| 1. Inserir no Inicio. |n");
165 printf("n| 2. Inserir no Fim. |n");
166 printf("n| 3. Inserir Antes de um Nó. |n");
167 printf("n| 4. Inserir Depois de um Nó. |n");
168 printf("n| 5. Inserir em Ordem Crescente. |n");
169 printf("n| 6. Inserir em Ordem DeCrescente. |n");
170 printf("n| 7. Inserir em Qualquer Lugar. |n");
171 printf("n|Digite a opção desejada: t");
172 scanf("%d%*c", &op);
173 return op;
174 }
175
176 //FUNÇÃO PARA CRIAR O MENU DE FUNÇÕES PARA REMOÇÃO
177 int menuRemover(void)
178 {
179 system("cls");
180 int op;
181 printf("n|----------------------------------------------------------------|n");
182 printf("n| MENU FUNÇÕES REMOÇÃO |n");
183 printf("n| 0. Sair. |n");
184 printf("n| 1. Remover do Inicio. |n");
185 printf("n| 2. Remover do Fim. |n");
186 printf("n| 3. Remover Antes de um Nó. |n");
187 printf("n| 4. Remover Depois de um Nó. |n");
188 printf("n| 5. Remover de qualquer lugar. |n");
189 printf("n|Digite a opção desejada: t");
190 scanf("%d%*c", &op);
191 return op;
192 }
193
194 //FUNÇÃO PARA CRIAR O MENU DE FUNÇÕES PARA PESQUISAR NÓS NA LISTA
195 int menuPesquisar(void)
196 {
197 system("cls");
198 int op;
199 printf("n|----------------------------------------------------------------|n");
200 printf("n| MENU FUNÇÕES PESQUISA |n");
201 printf("n| 0. Sair. |n");
202 printf("n| 1. Buscar um Nó. |n");
203 printf("n| 2. Encontrar o Maior elemento da lista. |n");
204 printf("n| 3. Encontrar o Menor elemento da lista. |n");
205 printf("n| 4. Nó Anterior a um Nó específico. |n");
206 printf("n| 5. Nó Posterior a um Nó específico. |n");
207 printf("n|Digite a opção desejada: t");
208 scanf("%d%*c", &op);
209 return op;
210 }
211
212 //FUNÇÃO PARA CRIAR O MENU DE FUNÇÕES PARA ATUALIZAR UM NÓ ESPECÍFICO DA LISTA
213 int menuAtualizar(void)
214 {
215 system("cls");
216 int op;
217 printf("n|----------------------------------------------------------------|n");
218 printf("n| MENU FUNÇÕES ATUALIZAR |n");
219 printf("n| 0. Sair. |n");
220 printf("n| 1. Atualizar um Nó. |n");
221 printf("n| 2. Atualizar um Nó Anterior a outro. |n");
222 printf("n| 3. Atualizar um Nó Posterior a outro. |n");
223 printf("n|Digite a opção desejada: t");
224 scanf("%d%*c", &op);
225 return op;
226 }
227
228 void opcaoPrincipal(no *LISTA, int op)
229 {
230 int opcao;
231 switch(op)
232 {
233 case 0:
234 printf("n SAINDO! nn");
235 libera(LISTA);
236 break;
237
238 case 1:
239 printf("nFUNÇÕES BÁSICASnn");
240 do
241 {
242 opcao = menuBasico();
243 opcaoBasico(LISTA, opcao);
244 getchar();
245 }
246 while(opcao);
247 break;
248
249 case 2:
250 printf("nFUNÇÕES PARA INSERÇÃOnn");
251 do
252 {
253 opcao = menuInserir();
254 opcaoInserir(LISTA , opcao);
255 getchar();
256 }
257 while(opcao);
258 break;
259
260 case 3:
261 printf("nFUNÇÕES PARA REMOÇÃOnn");
262 do
263 {
264 opcao = menuRemover();
265 opcaoRemover(LISTA , opcao);
266 getchar();
267 }
268 while(opcao);
269 break;
270
271 case 4:
272 printf("nFUNÇÕES PARA PESQUISARnn");
273 do
274 {
275 opcao = menuPesquisar();
276 opcaoPesquisar(LISTA , opcao);
277 getchar();
278 }
279 while(opcao);
280 break;
281
282 case 5:
283 printf("nFUNÇÕES PARA ATUALIZARnn");
284 do
285 {
286 opcao = menuAtualizar();
287 opcaoAtualizar(LISTA , opcao);
288 getchar();
289 }
290 while(opcao);
291 break;
292
293 default:
294 printf("nComando inválido!nn");
295 }
296 }
297
298 void opcaoBasico(no *LISTA , int op)
299 {
300 no *tmp;
301 switch(op)
302 {
303 case 0:
304 printf("n Aperte 0 (zero) novamente para voltar ao programa principal!nn");
305 break;
306
307 case 1:
308 printf("nZERANDO A LISTA");
309 libera(LISTA );
310 inicia(LISTA );
311 printf("nLista Zerada!nn");
312 break;
313
314 case 2:
315 printf("nQUANTIDADE TOTAL DE NÓS DA LISTA");
316 if(vazia(LISTA ))
317 printf("nA lista está vazia!nn");
318 else
319 printf("nA quantidade total de NÓS desta lista é: %d.nn", tam);
320 break;
321
322 case 3:
323 printf("nIMPRIMINDO OS NÓS DA LISTA - PONTEIRO ANTERIOR");
324 if(vazia(LISTA ))
325 printf("nA lista está vazia!nn");
326 else
327 imprimirAnterior(LISTA );
328 break;
329
330 case 4:
331 printf("nIMPRIMINDO OS NÓS DA LISTA - PONTEIRO POSTERIOR");
332 if(vazia(LISTA ))
333 printf("nA lista está vazia!nn");
334 else
335 imprimirPosterior(LISTA );
336 break;
337
338 case 5:
339 printf("nPRIMEIRO NÓ DA LISTA");
340 if(vazia(LISTA))
341 printf("nA lista está vazia!nn");
342 else
343 {
344 tmp = inicio(LISTA);
345 printf("nO nó do inicio da lista é: %3d. nn", tmp->num);
346 getchar();
347 }
348 break;
349
350 case 6:
351 printf("nÚLTIMO NÓ DA LISTA");
352 if(vazia(LISTA))
353 printf("nA lista está vazia!nn");
354 else
355 {
356 tmp = fim(LISTA);
357 printf("nO nó do fim da lista é: %3d. nn", tmp->num);
358 getchar();
359 }
360 break;
361
362 case 7:
363 printf("ÚNICO NÓ DA LISTA");
364 if(vazia(LISTA))
365 printf("nA lista está vazia!nn");
366 else
367 {
368 tmp = unico(LISTA);
369 if(tmp == NULL)
370 {
371 printf("n O nó não é o único da lista.");
372 }
373 else
374 {
375 printf("nO nó é o único da lista.");
376 }
377 getchar();
378 }
379 break;
380
381 default:
382 printf("nComando inválido!nn");
383 }
384 }
385
386 void opcaoInserir(no *LISTA, int op)
387 {
388 no *tmp;
389 switch(op)
390 {
391 case 0:
392 printf("n Aperte 0 (zero) novamente para voltar ao programa principal!nn");
393 break;
394
395 case 1:
396 printf("nINSERINDO UM NOVO NÓ NO INICIO DA LISTA");
397 tmp = insereInicio(LISTA);
398 printf("nNó inserido com sucesso: %3d. nn", tmp->num);
399 getchar();
400 break;
401
402 case 2:
403 printf("nINSERINDO UM NOVO NÓ NO FIM DA LISTA");
404 tmp = insereFim(LISTA);
405 printf("nNó inserido com sucesso: %3d. nn", tmp->num);
406 getchar();
407 break;
408
409 case 3:
410 printf("n INSERINDO UM NOVO NÓ ANTERIOR A OUTRO");
411 insereAnterior(LISTA);
412 printf("nNó inserido com sucesso: %3d. nn", tmp->num);
413 getchar();
414 break;
415
416 case 4:
417 printf("n INSERINDO UM NOVO NÓ POSTERIOR A OUTRO");
418 inserePosterior(LISTA);
419 break;
420
421 case 5:
422 printf("n INSERINDO UM NOVO NÓ EM ORDEM CRESCENTE");
423 insereEmOrdemCrescente(LISTA);
424 break;
425
426 case 6:
427 printf("n INSERINDO UM NOVO NÓ EM ORDEM DECRESCENTE");
428 insereEmOrdemDecrescente(LISTA);
429 break;
430
431 default:
432 printf("nComando inválido!nn");
433 }
434 }
435
436 void opcaoRemover(no *LISTA, int op)
437 {
438 no * tmp;
439 switch(op)
440 {
441 case 0:
442 printf("n Aperte 0 (zero) novamente para voltar ao programa principal!nn");
443 break;
444
445 case 1:
446 printf("nRETIRANDO UM ELEMENTO DO INICIO DA LISTA");
447 if(vazia(LISTA))
448 printf("nA lista está vazia!nn");
449 else
450 {
451 tmp = removeInicio(LISTA);
452 printf("nRetirado: %3d. nn", tmp->num);
453 getchar();
454 }
455 break;
456
457 case 2:
458 printf("nRETIRANDO UM ELEMENTO DO FIM DA LISTA");
459 if(vazia(LISTA))
460 {
461 printf("nA lista está vazia! nn");
462 }
463 else
464 {
465 tmp = removeFim(LISTA);
466 printf("nRetirado: %3d. nn", tmp->num);
467 getchar();
468 }
469 break;
470
471 case 3:
472 printf("nRETIRANDO UM ELEMENTO ANTERIOR A OUTRO");
473 if(vazia(LISTA))
474 {
475 printf("nA lista está vazia! nn");
476 }
477 else
478 {
479 removeAnterior(LISTA);
480 }
481 getchar();
482 break;
483
484 case 4:
485 printf("nRETIRANDO UM ELEMENTO POSTERIOR A OUTRO");
486 if(vazia(LISTA))
487 {
488 printf("nA lista está vazia! nn");
489 }
490 else
491 {
492 removePosterior(LISTA);
493 }
494 getchar();
495 break;
496
497 case 5:
498 printf("nRETIRANDO UM ELEMENTO DE QUALQUER LUGAR DA LISTA");
499 if(vazia(LISTA))
500 {
501 printf("nA lista está vazia! nn");
502 }
503 else
504 {
505 removerAny(LISTA);
506 }
507 getchar();
508 break;
509
510 default:
511 printf("nComando inválido! nn");
512 }
513 }
514
515 void opcaoPesquisar(no *LISTA, int op)
516 {
517 no *tmp;
518 int res;
519 switch(op)
520 {
521 case 0:
522 printf("n Aperte 0 (zero) novamente para voltar ao programa principal!nn");
523 break;
524
525 case 1:
526 printf("nBUSCANDO UM NÓ nn");
527 if(vazia(LISTA))
528 printf("nA lista está vazia! nn");
529 else
530 {
531 tmp = buscar(LISTA);
532 if(tmp == NULL)
533 printf("nO valor NÃO foi encontradonn");
534 else
535 {
536 printf("nO valor foi encontrado: %d nn", tmp->num);
537 }
538 }
539 getchar();
540 break;
541
542 case 2:
543 printf("nPESQUISANDO O MAIOR ELEMENTO DA LISTA");
544 if(vazia(LISTA))
545 printf("nA lista está vazia! nn");
546 else
547 {
548 res = pesquisaMaior(LISTA);
549 printf("nO maior elemento da lista é: %d. nn", res);
550 getchar();
551 }
552 break;
553
554 case 3:
555 printf("nPESQUISANDO O MENOR ELEMENTO DA LISTA");
556 if(vazia(LISTA))
557 printf("nA lista está vazia! nn");
558 else
559 {
560 res = pesquisaMenor(LISTA);
561 printf("nO menor elemento da lista é: %d. nn", res);
562 getchar();
563 }
564 break;
565
566 case 4:
567 printf("nOBTENDO O VALOR DO NÓ ANTERIOR");
568 if(vazia(LISTA))
569 printf("nA lista está vazia! nn");
570 else
571 noAnterior(LISTA);
572 getchar();
573 break;
574
575 case 5:
576 printf("nOBTENDO O VALOR DO NÓ POSTERIOR");
577 if(vazia(LISTA))
578 printf("nA lista está vazia! nn");
579 else
580 noPosterior(LISTA);
581 getchar();
582 break;
583
584 default:
585 printf("nComando inválido! nn");
586 }
587 }
588
589 void opcaoAtualizar(no *LISTA, int op)
590 {
591 switch(op)
592 {
593 case 0:
594 printf("n Aperte 0 (zero) novamente para voltar ao programa principal!nn");
595 break;
596
597 case 1:
598 printf("nATUALIZANDO UM VALOR DE UM NÓ DA LISTA");
599 if(vazia(LISTA))
600 printf("nA lista está vazia! nn");
601 else
602 atualizar(LISTA);
603 getchar();
604 break;
605
606 case 2:
607 printf("nATUALIZANDO UM NÓ ANTERIOR A OUTRO");
608 if(vazia(LISTA))
609 printf("nA lista está vazia! nn");
610 else
611 atualizarAnterior(LISTA);
612 getchar();
613 break;
614
615 case 3:
616 printf("nATUALIZANDO UM NÓ POSTERIOR A OUTRO");
617 if(vazia(LISTA))
618 printf("nA lista está vazia! nn");
619 else
620 atualizarPosterior(LISTA);
621 getchar();
622 break;
623
624 default:
625 printf("nComando inválido! nn");
626 }
627 }
628
629 /* FUNÇÃO PARA VERIFICAR SE A LISTA ESTÁ VAZIA */
630 int vazia(no *LISTA)
631 {
632 if((LISTA->prox==NULL)&&(LISTA->ant==NULL))
633 {
634 return 1;
635 }
636 else
637 return 0;
638 }
639
640 /* FUNÇÃO PARA ALOCAR UM NOVO NÓ */
641 no *aloca()
642 {
643 no *novo=(no *) malloc(sizeof(no));
644 if(!novo)
645 {
646 printf("nSem memória disponível! n");
647 exit(1);
648 }
649 else
650 {
651 novo->ant = NULL;
652 novo->prox = NULL;
653 printf("nNovo nó: ");
654 scanf("%d", &novo->num);
655 return novo;
656 }
657 }
658
659 /* ======================================================================
660 FUNÇÕES PARA INSERIR */
661
662 /* FUNÇÃO PARA INSERIR NO FIM DA LISTA */
663 no *insereFim(no *LISTA)
664 {
665 no *novo = aloca();
666
667 if(vazia(LISTA))
668 {
669 LISTA->prox = novo;
670 novo->ant = LISTA;
671 }
672 else
673 {
674 no *aux = LISTA->prox;
675 while(aux->prox != NULL)
676 aux = aux->prox;
677 novo->ant = aux;
678 aux->prox = novo;
679 novo->prox = NULL;
680 }
681 tam++;
682 return novo;
683 }
684
685 /* FUNÇÃO PARA INSERIR NO INICIO DA LISTA */
686 no *insereInicio(no *LISTA)
687 {
688 no *novo = aloca();
689 if(vazia(LISTA))
690 {
691 LISTA->prox = novo;
692 novo->ant = LISTA;
693 } else {
694 no *aux = LISTA->prox;
695 LISTA->prox = novo;
696 aux->ant = novo;
697 novo->ant = LISTA;
698 novo->prox = aux;
699 }
700 tam++;
701 return novo;
702 }
703
704 /* FUNÇÃO PARA INSERIR ANTES DE UM NÓ ESPECÍFICO DA LISTA */
705 void insereAnterior(no *LISTA)
706 {
707 printf("nDigite um valor a ser procurado: ");
708 scanf("%d", &x);
709 no *aux1, *aux2, *aux3;
710 while((LISTA != NULL) && (LISTA->num != x))
711 {
712 aux1 = LISTA;
713 aux2 = LISTA->ant;
714 LISTA = LISTA->prox;
715 aux3 = aux1->ant;
716 }
717 no *novo = aloca();
718 tam++;
719 printf("nInserido %3d. n", novo->num);
720 }
721
722 /* FUNÇÃO PARA INSERIR DEPOIS DE UM NÓ ESPECÍFICO DA LISTA */
723 void inserePosterior(no *LISTA)
724 {
725 printf("nDigite um valor a ser procurado: ");
726 scanf("%d", &x);
727 no *aux1 = LISTA, *aux2, *aux3;
728 while((aux1 != NULL) && (aux1->num != x))
729 {
730 aux1 = aux1->prox;
731 aux2 = aux1->prox;
732 aux3 = aux2->prox;
733 }
734 no *novo = aloca();
735 printf("nInserido: %3d. n", novo->num);
736 tam++;
737 }
738
739 /* FUNÇÃO PARA INSERIR EM ORDEM CRESCENTE */
740 void insereEmOrdemCrescente(no *LISTA)
741 {
742 printf("n implementar ");
743
744 }
745
746 /* FUNÇÃO PARA INSERIR EM ORDEM DECRESCENTE */
747 void insereEmOrdemDecrescente(no *LISTA)
748 {
749 printf("n implementar ");
750
751 }
752
753 /* ===============================================================
754 FUNÇÕES PARA IMPRIMIR NÓS DA LISTA */
755
756 /* FUNÇÃO PARA IMPRIMIR OS ELEMENTOS DE UMA LISTA - PONTEIRO ANTERIOR */
757 void imprimirAnterior(no *LISTA)
758 {
759 printf("n implementar ");
760 }
761
762 /* FUNÇÃO PARA IMPRIMIR OS ELEMENTOS DE UMA LISTA - PONTEIRO POSTERIOR */
763 void imprimirPosterior(no *LISTA)
764 {
765 no *tmp;
766 tmp = LISTA-> prox ;
767 printf("nLista:");
768 while( tmp != NULL)
769 {
770 printf("%5d", tmp-> num);
771 tmp = tmp-> prox ;
772 }
773 printf("n ");
774 int count;
775 for(count= 0 ; count < tam ; count++)
776 printf(" ^ ");
777 printf("nOrdem:");
778 for(count= 0 ; count < tam ; count++)
779 printf("%5d", count+1);
780 printf("nn");
781 }
782
783 /* FUNÇÃO PARA LIBERAR A LISTA */
784 void libera(no *LISTA)
785 {
786 if(!vazia(LISTA))
787 {
788 no *proxNo, *atual, *antNo;
789 atual = LISTA;
790 while(atual!= NULL)
791 {
792 proxNo = atual-> prox ;
793 antNo = atual-> ant;
794 free(atual);
795 atual = proxNo;
796 }
797 }
798 }
799
800
801 /* ===============================================================
802 FUNÇÕES PARA REMOVER NÓS*/
803
804 /* FUNÇÃO PARA REMOVER NÓS DO INICIO DA LISTA */
805 no *removeInicio(no *LISTA)
806 {
807 no *aux = LISTA-> prox ;
808 LISTA-> prox = aux-> prox ;
809 LISTA-> ant = NULL;
810 tam--;
811 return aux;
812 }
813
814 /* FUNÇÃO PARA REMOVER NÓS DO FIM DA LISTA */
815 no *removeFim(no *LISTA)
816 {
817 no *ultimo = LISTA-> prox , *penultimo = LISTA;
818 while(ultimo-> prox != NULL)
819 {
820 penultimo = ultimo;
821 ultimo = ultimo-> prox ;
822 }
823 penultimo-> prox = NULL;
824 penultimo-> ant = NULL;
825 tam--;
826 return ultimo;
827 }
828
829 /* FUNÇÃO PARA REMOVER UM NÓ ANTES DE OUTRO NÓ ESPECÍFICO */
830 void removeAnterior(no *LISTA)
831 {
832 printf("n implementar ");
833 }
834
835 /* FUNÇÃO PARA REMOVER UM NÓ DEPOIS DE OUTRO NÓ ESPECÍFICO */
836 void removePosterior(no *LISTA)
837 {
838 printf("nDigite um valor a ser procurado: ");
839 scanf("%d", &x);
840 no *aux1 = LISTA-> prox , *aux2 = LISTA, *aux3;
841 if((aux1->ant==NULL)&&(aux1->prox==NULL))
842 {
843 printf("n ÚNICO elemento da lista, não há posterior!");
844 }
845 else
846 {
847 while((aux1->prox != NULL) && (aux1->num != x))
848 {
849 printf("n dentro do while");
850 aux2 = aux1;
851 aux1 = aux1->prox;
852 aux2 = aux1->prox;
853 aux3 = aux2->prox;
854 }
855 printf("n AUX1 %d t AUX2 %d t AUX3 %d t", aux1->num, aux2->num, aux3->num);
856 printf("nRetirado: %3d. n", aux2->num);
857 aux1->prox = aux3;
858 aux3->ant = aux1;
859 aux2->ant = NULL;
860 aux2->prox = NULL;
861 tam--;
862 }
863 }
864
865 /* FUNÇÃO PARA REMOVER UM NÓ DE QUALQUER PARTE DA LISTA */
866 void removerAny(no *LISTA)
867 {
868 int opt,count;
869 printf("nQue posicao, [de 1 ate %d] voce deseja retirar: ", tam);
870 scanf("%d", &opt);
871
872 if(opt>0 && opt <= tam)
873 {
874 if(opt==1)
875 return removeInicio(LISTA);
876 else
877 {
878 no *atual = LISTA->prox, *anterior = LISTA;
879 for(count=1 ; count < opt ; count++)
880 {
881 anterior = atual;
882 atual = atual->prox;
883 }
884 anterior->prox = atual->prox;
885 tam--;
886 return atual;
887 }
888 printf("n Elemento removido com sucesso!! n");
889 }
890 else
891 {
892 printf("n Elemento inválido! n");
893 return NULL;
894 }
895 }
896
897 /* ===============================================================
898 FUNÇÕES PARA BUSCAR E ATUALIZAR NÓS DA LISTA */
899
900 /* FUNÇÃO PARA BUSCAR UM NÓ ESPECÍFICO */
901 no *buscar(no *LISTA)
902 {
903 printf("nDigite um valor a ser procurado: ");
904 scanf("%d", &x);
905 no *aux = LISTA->prox;
906 while((aux != NULL) && (aux->num != x) )
907 {
908 aux = aux->prox;
909 }
910 return aux;
911 }
912
913 /* FUNÇÃO PARA BUSCAR UM NÓ ANTERIOR A OUTRO */
914 void noAnterior(no *LISTA)
915 {
916 no *aux = buscar(LISTA);
917 if(aux == NULL)
918 {
919 printf("n O valor NÃO foi encontrado. n");
920 }
921 else
922 {
923 printf("n O valor foi encontrado: %d n", aux->num);
924 if(aux->ant==NULL)
925 {
926 printf("n Não existe nó anterior pois este é o primeiro nó da lista");
927 }
928 else
929 {
930 no *aux2 = aux->ant;
931 printf("n O nó anterior a este é: %d", aux2->num);
932 }
933 }
934 }
935
936 /* FUNÇÃO PARA BUSCAR UM NÓ POSTERIOR A OUTRO */
937 void noPosterior(no *LISTA)
938 {
939 no *aux = buscar(LISTA);
940 if(aux == NULL)
941 {
942 printf("n O valor NÃO foi encontrado. n");
943 }
944 else
945 {
946 printf("n O valor foi encontrado: %d n", aux->num);
947 if(aux->prox==NULL)
948 {
949 printf("n Não existe nó posterior pois este é o primeiro nó da lista");
950 }
951 else
952 {
953 no *aux2 = aux->prox;
954 printf("n O nó posterior a este é: %d", aux2->num);
955 }
956 }
957 }
958
959 /* FUNÇÃO PARA ATUALIZAR UM NÓ ESPECÍFICO */
960 void atualizar(no *LISTA)
961 {
962 no *aux = buscar(LISTA);
963 if(aux == NULL)
964 {
965 printf("n O valor NÃO foi encontrado. n");
966 }
967 else
968 {
969 printf("n O valor foi encontrado: %d n", aux->num);
970 printf("n Digite o novo valor: ");
971 scanf("%d", &aux->num);
972 printf("n O valor foi atualizado com sucesso! nn");
973 }
974 }
975
976 /* FUNÇÃO PARA ATUALIZAR UM NÓ POSTERIOR A OUTRO */
977 void atualizarPosterior(no *LISTA)
978 {
979 printf("n implementar ");
980 }
981
982 /* FUNÇÃO PARA ATUALIZAR UM NÓ ANTERIOR A OUTRO NÓ */
983 void atualizarAnterior(no *LISTA)
984 {
985 printf("n implementar ");
986 }
987
988 /* FUNÇÃO PARA PESQUISAR O MAIOR VALOR DA LISTA */
989 int pesquisaMaior(no *LISTA)
990 {
991 int maior = LISTA->num;
992 while(LISTA != NULL)
993 {
994 if(LISTA->num > maior)
995 maior = LISTA->num;
996 LISTA = LISTA->prox;
997 }
998 return maior;
999 }
1000
1001 /* FUNÇÃO PARA PESQUISAR O MENOR VALOR DA LISTA */
1002 int pesquisaMenor(no *LISTA)
1003 {
1004 LISTA = LISTA->prox;
1005 int menor = LISTA->num;
1006 while(LISTA != NULL)
1007 {
1008 if(LISTA->num < menor)
1009 menor = LISTA->num;
1010 LISTA = LISTA->prox;
1011 }
1012 return menor;
1013 }
1014
1015 no *fim(no *LISTA)
1016 {
1017 no *aux1 = LISTA->prox, *aux2 = LISTA;
1018
1019 if((aux1->ant == NULL) && (aux1->prox == NULL))
1020 {
1021 return aux1;
1022 }
1023 else
1024 {
1025 while(aux1->prox != NULL)
1026 {
1027 aux1 = aux1->prox;
1028 }
1029 aux2 = aux1;
1030 return aux2;
1031 }
1032 }
1033
1034 no *inicio(no *LISTA)
1035 {
1036 no *aux = LISTA->prox++;
1037 return aux;
1038 }
1039
1040 //VERIFICANDO SE O NÓ É O ÚNICO DA LISTA
1041 no *unico(no *LISTA)
1042 {
1043 no *aux = LISTA;
1044 if((aux->ant == NULL) && (aux->prox == NULL))
1045 {
1046 return aux;
1047 }
1048 else
1049 {
1050 return NULL;
1051 }
1052 }
1053

Mais conteúdo relacionado

Mais procurados

Aula de Parasitologia Médica sobre a Malária
Aula de Parasitologia Médica sobre a MaláriaAula de Parasitologia Médica sobre a Malária
Aula de Parasitologia Médica sobre a MaláriaJaqueline Almeida
 
Carcinogenese as bases moleculares do cancer
Carcinogenese as bases moleculares do cancerCarcinogenese as bases moleculares do cancer
Carcinogenese as bases moleculares do cancerVirgínia L. Sousa
 
Cultura e clima organizacional
Cultura e clima organizacionalCultura e clima organizacional
Cultura e clima organizacionalosvaldocostasoares
 
Agentes infecciosos e automedicação
Agentes infecciosos e automedicaçãoAgentes infecciosos e automedicação
Agentes infecciosos e automedicaçãoPatrícia Prates
 
TDC2017 - Misturando dados com Pentaho para insights mais significativos
TDC2017 - Misturando dados com Pentaho para insights mais significativosTDC2017 - Misturando dados com Pentaho para insights mais significativos
TDC2017 - Misturando dados com Pentaho para insights mais significativosAmbiente Livre
 
Aula 1 - Bioestatística
Aula 1 - BioestatísticaAula 1 - Bioestatística
Aula 1 - BioestatísticaCaroline Godoy
 
Questões de animais peçonhentos
Questões de animais peçonhentosQuestões de animais peçonhentos
Questões de animais peçonhentosNathy Oliveira
 
Semiologia 12 nefrologia - diagnóstico sindrômico em nefrologia pdf
Semiologia 12   nefrologia - diagnóstico sindrômico em nefrologia pdfSemiologia 12   nefrologia - diagnóstico sindrômico em nefrologia pdf
Semiologia 12 nefrologia - diagnóstico sindrômico em nefrologia pdfJucie Vasconcelos
 
Tecnologia do DNA recombinante
Tecnologia do DNA recombinanteTecnologia do DNA recombinante
Tecnologia do DNA recombinanteShaline Araújo
 
Questões 1 s 2° bimestre _com gabarito
Questões  1 s  2° bimestre _com gabaritoQuestões  1 s  2° bimestre _com gabarito
Questões 1 s 2° bimestre _com gabaritoIonara Urrutia Moura
 
Microbiologia aplicada aula03 microrganismos
Microbiologia aplicada aula03 microrganismosMicrobiologia aplicada aula03 microrganismos
Microbiologia aplicada aula03 microrganismosAmanda Fraga
 
Malaria - Plasmodium
Malaria - PlasmodiumMalaria - Plasmodium
Malaria - PlasmodiumFábio Baía
 
OXIURIOSE E TRICURÍASE
OXIURIOSE E TRICURÍASEOXIURIOSE E TRICURÍASE
OXIURIOSE E TRICURÍASEElaine Ramos
 
Estruturas organizacionais
Estruturas organizacionaisEstruturas organizacionais
Estruturas organizacionaisLuis Cunha
 

Mais procurados (20)

Aula de Parasitologia Médica sobre a Malária
Aula de Parasitologia Médica sobre a MaláriaAula de Parasitologia Médica sobre a Malária
Aula de Parasitologia Médica sobre a Malária
 
Os fungos
Os fungosOs fungos
Os fungos
 
Carcinogenese as bases moleculares do cancer
Carcinogenese as bases moleculares do cancerCarcinogenese as bases moleculares do cancer
Carcinogenese as bases moleculares do cancer
 
Cultura e clima organizacional
Cultura e clima organizacionalCultura e clima organizacional
Cultura e clima organizacional
 
Agentes infecciosos e automedicação
Agentes infecciosos e automedicaçãoAgentes infecciosos e automedicação
Agentes infecciosos e automedicação
 
TDC2017 - Misturando dados com Pentaho para insights mais significativos
TDC2017 - Misturando dados com Pentaho para insights mais significativosTDC2017 - Misturando dados com Pentaho para insights mais significativos
TDC2017 - Misturando dados com Pentaho para insights mais significativos
 
Aula 1 - Bioestatística
Aula 1 - BioestatísticaAula 1 - Bioestatística
Aula 1 - Bioestatística
 
Doenças Raras 2 parte
Doenças  Raras 2 parte Doenças  Raras 2 parte
Doenças Raras 2 parte
 
Questões de animais peçonhentos
Questões de animais peçonhentosQuestões de animais peçonhentos
Questões de animais peçonhentos
 
Toxoplasmose folder
Toxoplasmose folderToxoplasmose folder
Toxoplasmose folder
 
Semiologia 12 nefrologia - diagnóstico sindrômico em nefrologia pdf
Semiologia 12   nefrologia - diagnóstico sindrômico em nefrologia pdfSemiologia 12   nefrologia - diagnóstico sindrômico em nefrologia pdf
Semiologia 12 nefrologia - diagnóstico sindrômico em nefrologia pdf
 
Tecnologia do DNA recombinante
Tecnologia do DNA recombinanteTecnologia do DNA recombinante
Tecnologia do DNA recombinante
 
Questões 1 s 2° bimestre _com gabarito
Questões  1 s  2° bimestre _com gabaritoQuestões  1 s  2° bimestre _com gabarito
Questões 1 s 2° bimestre _com gabarito
 
Microbiologia aplicada aula03 microrganismos
Microbiologia aplicada aula03 microrganismosMicrobiologia aplicada aula03 microrganismos
Microbiologia aplicada aula03 microrganismos
 
Malaria - Plasmodium
Malaria - PlasmodiumMalaria - Plasmodium
Malaria - Plasmodium
 
OXIURIOSE E TRICURÍASE
OXIURIOSE E TRICURÍASEOXIURIOSE E TRICURÍASE
OXIURIOSE E TRICURÍASE
 
45 evolucao
45 evolucao45 evolucao
45 evolucao
 
Toxoplasmose
ToxoplasmoseToxoplasmose
Toxoplasmose
 
Micose
MicoseMicose
Micose
 
Estruturas organizacionais
Estruturas organizacionaisEstruturas organizacionais
Estruturas organizacionais
 

Semelhante a Implementação de Lista Duplamente Encadeada (LDE) em C

Semelhante a Implementação de Lista Duplamente Encadeada (LDE) em C (14)

Lista simplesmente encadeada
Lista simplesmente encadeada Lista simplesmente encadeada
Lista simplesmente encadeada
 
Lista simplesmente encadeada dinamica
Lista simplesmente encadeada dinamicaLista simplesmente encadeada dinamica
Lista simplesmente encadeada dinamica
 
Lista sequencial estatica
Lista sequencial estaticaLista sequencial estatica
Lista sequencial estatica
 
Lista duplamente encadeada dinamica
Lista duplamente encadeada dinamicaLista duplamente encadeada dinamica
Lista duplamente encadeada dinamica
 
Aula6 - Linguagem C
Aula6 - Linguagem CAula6 - Linguagem C
Aula6 - Linguagem C
 
Fila circular dinamica
Fila circular dinamicaFila circular dinamica
Fila circular dinamica
 
Árvore Binária
Árvore BináriaÁrvore Binária
Árvore Binária
 
Tabela Hash com Lista Encadeada
Tabela Hash com Lista EncadeadaTabela Hash com Lista Encadeada
Tabela Hash com Lista Encadeada
 
Pilha em C
Pilha em CPilha em C
Pilha em C
 
Arvore binária
Arvore bináriaArvore binária
Arvore binária
 
Lista duplamente encadeada dinâmica circular
Lista duplamente encadeada dinâmica circularLista duplamente encadeada dinâmica circular
Lista duplamente encadeada dinâmica circular
 
Java hidden features
Java hidden featuresJava hidden features
Java hidden features
 
Lista simplesmente encadeada dinâmica circular
Lista simplesmente encadeada dinâmica circularLista simplesmente encadeada dinâmica circular
Lista simplesmente encadeada dinâmica circular
 
Estruturas de dados Revisão de C
Estruturas de dados Revisão de CEstruturas de dados Revisão de C
Estruturas de dados Revisão de C
 

Mais de Elaine Cecília Gatto

A influência da Tecnologia em cada faixa etaria
A influência da Tecnologia em cada faixa etariaA influência da Tecnologia em cada faixa etaria
A influência da Tecnologia em cada faixa etariaElaine Cecília Gatto
 
Inteligência Artificial Aplicada à Medicina
Inteligência Artificial Aplicada à MedicinaInteligência Artificial Aplicada à Medicina
Inteligência Artificial Aplicada à MedicinaElaine Cecília Gatto
 
Além do Aprendizado Local e Global: Particionando o espaço de classes em prob...
Além do Aprendizado Local e Global: Particionando o espaço de classes em prob...Além do Aprendizado Local e Global: Particionando o espaço de classes em prob...
Além do Aprendizado Local e Global: Particionando o espaço de classes em prob...Elaine Cecília Gatto
 
Apresentação da minha tese de doutorado no EPPC
Apresentação da minha tese de doutorado no EPPCApresentação da minha tese de doutorado no EPPC
Apresentação da minha tese de doutorado no EPPCElaine Cecília Gatto
 
Como a pesquisa científica impacta o mundo real.pptx
Como a pesquisa científica impacta o mundo real.pptxComo a pesquisa científica impacta o mundo real.pptx
Como a pesquisa científica impacta o mundo real.pptxElaine Cecília Gatto
 
Explorando correlações entre rótulos para o particionamento do espaço de rótu...
Explorando correlações entre rótulos para o particionamento do espaço de rótu...Explorando correlações entre rótulos para o particionamento do espaço de rótu...
Explorando correlações entre rótulos para o particionamento do espaço de rótu...Elaine Cecília Gatto
 
Community Detection for Multi-Label Classification - Seminários UFSCar
Community Detection for Multi-Label Classification - Seminários UFSCarCommunity Detection for Multi-Label Classification - Seminários UFSCar
Community Detection for Multi-Label Classification - Seminários UFSCarElaine Cecília Gatto
 
Classificação Multirrótulo: Aprendizado de Correlações
Classificação Multirrótulo: Aprendizado de CorrelaçõesClassificação Multirrótulo: Aprendizado de Correlações
Classificação Multirrótulo: Aprendizado de CorrelaçõesElaine Cecília Gatto
 
EXPLORANDO CORRELAÇÕES PARA O PARTICIONAMENTO DO ESPAÇO DE RÓTULOS EM PROBLEM...
EXPLORANDO CORRELAÇÕES PARA O PARTICIONAMENTO DO ESPAÇO DE RÓTULOS EM PROBLEM...EXPLORANDO CORRELAÇÕES PARA O PARTICIONAMENTO DO ESPAÇO DE RÓTULOS EM PROBLEM...
EXPLORANDO CORRELAÇÕES PARA O PARTICIONAMENTO DO ESPAÇO DE RÓTULOS EM PROBLEM...Elaine Cecília Gatto
 
Community Detection Method for Multi-Label Classification
Community Detection Method for Multi-Label ClassificationCommunity Detection Method for Multi-Label Classification
Community Detection Method for Multi-Label ClassificationElaine Cecília Gatto
 
Mulheres na Campus Party assumir o feminismo ou não – Blogueiras Feministas.pdf
Mulheres na Campus Party assumir o feminismo ou não – Blogueiras Feministas.pdfMulheres na Campus Party assumir o feminismo ou não – Blogueiras Feministas.pdf
Mulheres na Campus Party assumir o feminismo ou não – Blogueiras Feministas.pdfElaine Cecília Gatto
 
Explorando Correlações entre Rótulos usando Métodos de Detecção de Comu...
Explorando Correlações entre Rótulos usando Métodos de Detecção de Comu...Explorando Correlações entre Rótulos usando Métodos de Detecção de Comu...
Explorando Correlações entre Rótulos usando Métodos de Detecção de Comu...Elaine Cecília Gatto
 
EXPLORANDO CORRELAÇÕES PARA O PARTICIONAMENTO DO ESPAÇO DE RÓTULOS EM PROBLEM...
EXPLORANDO CORRELAÇÕES PARA O PARTICIONAMENTO DO ESPAÇO DE RÓTULOS EM PROBLEM...EXPLORANDO CORRELAÇÕES PARA O PARTICIONAMENTO DO ESPAÇO DE RÓTULOS EM PROBLEM...
EXPLORANDO CORRELAÇÕES PARA O PARTICIONAMENTO DO ESPAÇO DE RÓTULOS EM PROBLEM...Elaine Cecília Gatto
 
Pipeline desdobramento escalonamento
Pipeline desdobramento escalonamentoPipeline desdobramento escalonamento
Pipeline desdobramento escalonamentoElaine Cecília Gatto
 
Resumo das Instruções de Desvio Incondicionais MIPS 32 bits
Resumo das Instruções de Desvio Incondicionais MIPS 32 bitsResumo das Instruções de Desvio Incondicionais MIPS 32 bits
Resumo das Instruções de Desvio Incondicionais MIPS 32 bitsElaine Cecília Gatto
 
Como descobrir e classificar coisas usando machine learning sem compilcação
Como descobrir e classificar coisas usando machine learning sem compilcaçãoComo descobrir e classificar coisas usando machine learning sem compilcação
Como descobrir e classificar coisas usando machine learning sem compilcaçãoElaine Cecília Gatto
 

Mais de Elaine Cecília Gatto (20)

A influência da Tecnologia em cada faixa etaria
A influência da Tecnologia em cada faixa etariaA influência da Tecnologia em cada faixa etaria
A influência da Tecnologia em cada faixa etaria
 
Inteligência Artificial Aplicada à Medicina
Inteligência Artificial Aplicada à MedicinaInteligência Artificial Aplicada à Medicina
Inteligência Artificial Aplicada à Medicina
 
Além do Aprendizado Local e Global: Particionando o espaço de classes em prob...
Além do Aprendizado Local e Global: Particionando o espaço de classes em prob...Além do Aprendizado Local e Global: Particionando o espaço de classes em prob...
Além do Aprendizado Local e Global: Particionando o espaço de classes em prob...
 
Apresentação da minha tese de doutorado no EPPC
Apresentação da minha tese de doutorado no EPPCApresentação da minha tese de doutorado no EPPC
Apresentação da minha tese de doutorado no EPPC
 
entrevista r7.pdf
entrevista r7.pdfentrevista r7.pdf
entrevista r7.pdf
 
Como a pesquisa científica impacta o mundo real.pptx
Como a pesquisa científica impacta o mundo real.pptxComo a pesquisa científica impacta o mundo real.pptx
Como a pesquisa científica impacta o mundo real.pptx
 
Empoderamento Feminino
Empoderamento FemininoEmpoderamento Feminino
Empoderamento Feminino
 
Explorando correlações entre rótulos para o particionamento do espaço de rótu...
Explorando correlações entre rótulos para o particionamento do espaço de rótu...Explorando correlações entre rótulos para o particionamento do espaço de rótu...
Explorando correlações entre rótulos para o particionamento do espaço de rótu...
 
Community Detection for Multi-Label Classification - Seminários UFSCar
Community Detection for Multi-Label Classification - Seminários UFSCarCommunity Detection for Multi-Label Classification - Seminários UFSCar
Community Detection for Multi-Label Classification - Seminários UFSCar
 
Classificação Multirrótulo: Aprendizado de Correlações
Classificação Multirrótulo: Aprendizado de CorrelaçõesClassificação Multirrótulo: Aprendizado de Correlações
Classificação Multirrótulo: Aprendizado de Correlações
 
EXPLORANDO CORRELAÇÕES PARA O PARTICIONAMENTO DO ESPAÇO DE RÓTULOS EM PROBLEM...
EXPLORANDO CORRELAÇÕES PARA O PARTICIONAMENTO DO ESPAÇO DE RÓTULOS EM PROBLEM...EXPLORANDO CORRELAÇÕES PARA O PARTICIONAMENTO DO ESPAÇO DE RÓTULOS EM PROBLEM...
EXPLORANDO CORRELAÇÕES PARA O PARTICIONAMENTO DO ESPAÇO DE RÓTULOS EM PROBLEM...
 
Community Detection Method for Multi-Label Classification
Community Detection Method for Multi-Label ClassificationCommunity Detection Method for Multi-Label Classification
Community Detection Method for Multi-Label Classification
 
Mulheres na Campus Party assumir o feminismo ou não – Blogueiras Feministas.pdf
Mulheres na Campus Party assumir o feminismo ou não – Blogueiras Feministas.pdfMulheres na Campus Party assumir o feminismo ou não – Blogueiras Feministas.pdf
Mulheres na Campus Party assumir o feminismo ou não – Blogueiras Feministas.pdf
 
Curtinhas de sábado.pdf
Curtinhas de sábado.pdfCurtinhas de sábado.pdf
Curtinhas de sábado.pdf
 
Explorando Correlações entre Rótulos usando Métodos de Detecção de Comu...
Explorando Correlações entre Rótulos usando Métodos de Detecção de Comu...Explorando Correlações entre Rótulos usando Métodos de Detecção de Comu...
Explorando Correlações entre Rótulos usando Métodos de Detecção de Comu...
 
EXPLORANDO CORRELAÇÕES PARA O PARTICIONAMENTO DO ESPAÇO DE RÓTULOS EM PROBLEM...
EXPLORANDO CORRELAÇÕES PARA O PARTICIONAMENTO DO ESPAÇO DE RÓTULOS EM PROBLEM...EXPLORANDO CORRELAÇÕES PARA O PARTICIONAMENTO DO ESPAÇO DE RÓTULOS EM PROBLEM...
EXPLORANDO CORRELAÇÕES PARA O PARTICIONAMENTO DO ESPAÇO DE RÓTULOS EM PROBLEM...
 
Pipeline desdobramento escalonamento
Pipeline desdobramento escalonamentoPipeline desdobramento escalonamento
Pipeline desdobramento escalonamento
 
Cheat sheet Mips 32 bits
Cheat sheet Mips 32 bitsCheat sheet Mips 32 bits
Cheat sheet Mips 32 bits
 
Resumo das Instruções de Desvio Incondicionais MIPS 32 bits
Resumo das Instruções de Desvio Incondicionais MIPS 32 bitsResumo das Instruções de Desvio Incondicionais MIPS 32 bits
Resumo das Instruções de Desvio Incondicionais MIPS 32 bits
 
Como descobrir e classificar coisas usando machine learning sem compilcação
Como descobrir e classificar coisas usando machine learning sem compilcaçãoComo descobrir e classificar coisas usando machine learning sem compilcação
Como descobrir e classificar coisas usando machine learning sem compilcação
 

Último

Revolução russa e mexicana. Slides explicativos e atividades
Revolução russa e mexicana. Slides explicativos e atividadesRevolução russa e mexicana. Slides explicativos e atividades
Revolução russa e mexicana. Slides explicativos e atividadesFabianeMartins35
 
Slides Lição 5, Betel, Ordenança para uma vida de vigilância e oração, 2Tr24....
Slides Lição 5, Betel, Ordenança para uma vida de vigilância e oração, 2Tr24....Slides Lição 5, Betel, Ordenança para uma vida de vigilância e oração, 2Tr24....
Slides Lição 5, Betel, Ordenança para uma vida de vigilância e oração, 2Tr24....LuizHenriquedeAlmeid6
 
COMPETÊNCIA 4 NO ENEM: O TEXTO E SUAS AMARRACÕES
COMPETÊNCIA 4 NO ENEM: O TEXTO E SUAS AMARRACÕESCOMPETÊNCIA 4 NO ENEM: O TEXTO E SUAS AMARRACÕES
COMPETÊNCIA 4 NO ENEM: O TEXTO E SUAS AMARRACÕESEduardaReis50
 
Reta Final - CNU - Gestão Governamental - Prof. Stefan Fantini.pdf
Reta Final - CNU - Gestão Governamental - Prof. Stefan Fantini.pdfReta Final - CNU - Gestão Governamental - Prof. Stefan Fantini.pdf
Reta Final - CNU - Gestão Governamental - Prof. Stefan Fantini.pdfWagnerCamposCEA
 
PROVA - ESTUDO CONTEMPORÂNEO E TRANSVERSAL: LEITURA DE IMAGENS, GRÁFICOS E MA...
PROVA - ESTUDO CONTEMPORÂNEO E TRANSVERSAL: LEITURA DE IMAGENS, GRÁFICOS E MA...PROVA - ESTUDO CONTEMPORÂNEO E TRANSVERSAL: LEITURA DE IMAGENS, GRÁFICOS E MA...
PROVA - ESTUDO CONTEMPORÂNEO E TRANSVERSAL: LEITURA DE IMAGENS, GRÁFICOS E MA...azulassessoria9
 
DeClara n.º 75 Abril 2024 - O Jornal digital do Agrupamento de Escolas Clara ...
DeClara n.º 75 Abril 2024 - O Jornal digital do Agrupamento de Escolas Clara ...DeClara n.º 75 Abril 2024 - O Jornal digital do Agrupamento de Escolas Clara ...
DeClara n.º 75 Abril 2024 - O Jornal digital do Agrupamento de Escolas Clara ...IsabelPereira2010
 
Nós Propomos! " Pinhais limpos, mundo saudável"
Nós Propomos! " Pinhais limpos, mundo saudável"Nós Propomos! " Pinhais limpos, mundo saudável"
Nós Propomos! " Pinhais limpos, mundo saudável"Ilda Bicacro
 
Rota das Ribeiras Camp, Projeto Nós Propomos!
Rota das Ribeiras Camp, Projeto Nós Propomos!Rota das Ribeiras Camp, Projeto Nós Propomos!
Rota das Ribeiras Camp, Projeto Nós Propomos!Ilda Bicacro
 
2° ANO - ENSINO FUNDAMENTAL ENSINO RELIGIOSO
2° ANO - ENSINO FUNDAMENTAL ENSINO RELIGIOSO2° ANO - ENSINO FUNDAMENTAL ENSINO RELIGIOSO
2° ANO - ENSINO FUNDAMENTAL ENSINO RELIGIOSOLeloIurk1
 
"É melhor praticar para a nota" - Como avaliar comportamentos em contextos de...
"É melhor praticar para a nota" - Como avaliar comportamentos em contextos de..."É melhor praticar para a nota" - Como avaliar comportamentos em contextos de...
"É melhor praticar para a nota" - Como avaliar comportamentos em contextos de...Rosalina Simão Nunes
 
PROVA - ESTUDO CONTEMPORÂNEO E TRANSVERSAL: LEITURA DE IMAGENS, GRÁFICOS E MA...
PROVA - ESTUDO CONTEMPORÂNEO E TRANSVERSAL: LEITURA DE IMAGENS, GRÁFICOS E MA...PROVA - ESTUDO CONTEMPORÂNEO E TRANSVERSAL: LEITURA DE IMAGENS, GRÁFICOS E MA...
PROVA - ESTUDO CONTEMPORÂNEO E TRANSVERSAL: LEITURA DE IMAGENS, GRÁFICOS E MA...azulassessoria9
 
Introdução a Caminhada do Interior......
Introdução a Caminhada do Interior......Introdução a Caminhada do Interior......
Introdução a Caminhada do Interior......suporte24hcamin
 
Estudar, para quê? Ciência, para quê? Parte 1 e Parte 2
Estudar, para quê?  Ciência, para quê? Parte 1 e Parte 2Estudar, para quê?  Ciência, para quê? Parte 1 e Parte 2
Estudar, para quê? Ciência, para quê? Parte 1 e Parte 2Maria Teresa Thomaz
 
Dicionário de Genealogia, autor Gilber Rubim Rangel
Dicionário de Genealogia, autor Gilber Rubim RangelDicionário de Genealogia, autor Gilber Rubim Rangel
Dicionário de Genealogia, autor Gilber Rubim RangelGilber Rubim Rangel
 
o ciclo do contato Jorge Ponciano Ribeiro.pdf
o ciclo do contato Jorge Ponciano Ribeiro.pdfo ciclo do contato Jorge Ponciano Ribeiro.pdf
o ciclo do contato Jorge Ponciano Ribeiro.pdfCamillaBrito19
 
A QUATRO MÃOS - MARILDA CASTANHA . pdf
A QUATRO MÃOS  -  MARILDA CASTANHA . pdfA QUATRO MÃOS  -  MARILDA CASTANHA . pdf
A QUATRO MÃOS - MARILDA CASTANHA . pdfAna Lemos
 
Slides Lição 05, Central Gospel, A Grande Tribulação, 1Tr24.pptx
Slides Lição 05, Central Gospel, A Grande Tribulação, 1Tr24.pptxSlides Lição 05, Central Gospel, A Grande Tribulação, 1Tr24.pptx
Slides Lição 05, Central Gospel, A Grande Tribulação, 1Tr24.pptxLuizHenriquedeAlmeid6
 
PROVA - ESTUDO CONTEMPORÂNEO E TRANSVERSAL: COMUNICAÇÃO ASSERTIVA E INTERPESS...
PROVA - ESTUDO CONTEMPORÂNEO E TRANSVERSAL: COMUNICAÇÃO ASSERTIVA E INTERPESS...PROVA - ESTUDO CONTEMPORÂNEO E TRANSVERSAL: COMUNICAÇÃO ASSERTIVA E INTERPESS...
PROVA - ESTUDO CONTEMPORÂNEO E TRANSVERSAL: COMUNICAÇÃO ASSERTIVA E INTERPESS...azulassessoria9
 
PRÉDIOS HISTÓRICOS DE ASSARÉ Prof. Francisco Leite.pdf
PRÉDIOS HISTÓRICOS DE ASSARÉ Prof. Francisco Leite.pdfPRÉDIOS HISTÓRICOS DE ASSARÉ Prof. Francisco Leite.pdf
PRÉDIOS HISTÓRICOS DE ASSARÉ Prof. Francisco Leite.pdfprofesfrancleite
 
SLIDE DE Revolução Mexicana 1910 da disciplina cultura espanhola
SLIDE DE Revolução Mexicana 1910 da disciplina cultura espanholaSLIDE DE Revolução Mexicana 1910 da disciplina cultura espanhola
SLIDE DE Revolução Mexicana 1910 da disciplina cultura espanholacleanelima11
 

Último (20)

Revolução russa e mexicana. Slides explicativos e atividades
Revolução russa e mexicana. Slides explicativos e atividadesRevolução russa e mexicana. Slides explicativos e atividades
Revolução russa e mexicana. Slides explicativos e atividades
 
Slides Lição 5, Betel, Ordenança para uma vida de vigilância e oração, 2Tr24....
Slides Lição 5, Betel, Ordenança para uma vida de vigilância e oração, 2Tr24....Slides Lição 5, Betel, Ordenança para uma vida de vigilância e oração, 2Tr24....
Slides Lição 5, Betel, Ordenança para uma vida de vigilância e oração, 2Tr24....
 
COMPETÊNCIA 4 NO ENEM: O TEXTO E SUAS AMARRACÕES
COMPETÊNCIA 4 NO ENEM: O TEXTO E SUAS AMARRACÕESCOMPETÊNCIA 4 NO ENEM: O TEXTO E SUAS AMARRACÕES
COMPETÊNCIA 4 NO ENEM: O TEXTO E SUAS AMARRACÕES
 
Reta Final - CNU - Gestão Governamental - Prof. Stefan Fantini.pdf
Reta Final - CNU - Gestão Governamental - Prof. Stefan Fantini.pdfReta Final - CNU - Gestão Governamental - Prof. Stefan Fantini.pdf
Reta Final - CNU - Gestão Governamental - Prof. Stefan Fantini.pdf
 
PROVA - ESTUDO CONTEMPORÂNEO E TRANSVERSAL: LEITURA DE IMAGENS, GRÁFICOS E MA...
PROVA - ESTUDO CONTEMPORÂNEO E TRANSVERSAL: LEITURA DE IMAGENS, GRÁFICOS E MA...PROVA - ESTUDO CONTEMPORÂNEO E TRANSVERSAL: LEITURA DE IMAGENS, GRÁFICOS E MA...
PROVA - ESTUDO CONTEMPORÂNEO E TRANSVERSAL: LEITURA DE IMAGENS, GRÁFICOS E MA...
 
DeClara n.º 75 Abril 2024 - O Jornal digital do Agrupamento de Escolas Clara ...
DeClara n.º 75 Abril 2024 - O Jornal digital do Agrupamento de Escolas Clara ...DeClara n.º 75 Abril 2024 - O Jornal digital do Agrupamento de Escolas Clara ...
DeClara n.º 75 Abril 2024 - O Jornal digital do Agrupamento de Escolas Clara ...
 
Nós Propomos! " Pinhais limpos, mundo saudável"
Nós Propomos! " Pinhais limpos, mundo saudável"Nós Propomos! " Pinhais limpos, mundo saudável"
Nós Propomos! " Pinhais limpos, mundo saudável"
 
Rota das Ribeiras Camp, Projeto Nós Propomos!
Rota das Ribeiras Camp, Projeto Nós Propomos!Rota das Ribeiras Camp, Projeto Nós Propomos!
Rota das Ribeiras Camp, Projeto Nós Propomos!
 
2° ANO - ENSINO FUNDAMENTAL ENSINO RELIGIOSO
2° ANO - ENSINO FUNDAMENTAL ENSINO RELIGIOSO2° ANO - ENSINO FUNDAMENTAL ENSINO RELIGIOSO
2° ANO - ENSINO FUNDAMENTAL ENSINO RELIGIOSO
 
"É melhor praticar para a nota" - Como avaliar comportamentos em contextos de...
"É melhor praticar para a nota" - Como avaliar comportamentos em contextos de..."É melhor praticar para a nota" - Como avaliar comportamentos em contextos de...
"É melhor praticar para a nota" - Como avaliar comportamentos em contextos de...
 
PROVA - ESTUDO CONTEMPORÂNEO E TRANSVERSAL: LEITURA DE IMAGENS, GRÁFICOS E MA...
PROVA - ESTUDO CONTEMPORÂNEO E TRANSVERSAL: LEITURA DE IMAGENS, GRÁFICOS E MA...PROVA - ESTUDO CONTEMPORÂNEO E TRANSVERSAL: LEITURA DE IMAGENS, GRÁFICOS E MA...
PROVA - ESTUDO CONTEMPORÂNEO E TRANSVERSAL: LEITURA DE IMAGENS, GRÁFICOS E MA...
 
Introdução a Caminhada do Interior......
Introdução a Caminhada do Interior......Introdução a Caminhada do Interior......
Introdução a Caminhada do Interior......
 
Estudar, para quê? Ciência, para quê? Parte 1 e Parte 2
Estudar, para quê?  Ciência, para quê? Parte 1 e Parte 2Estudar, para quê?  Ciência, para quê? Parte 1 e Parte 2
Estudar, para quê? Ciência, para quê? Parte 1 e Parte 2
 
Dicionário de Genealogia, autor Gilber Rubim Rangel
Dicionário de Genealogia, autor Gilber Rubim RangelDicionário de Genealogia, autor Gilber Rubim Rangel
Dicionário de Genealogia, autor Gilber Rubim Rangel
 
o ciclo do contato Jorge Ponciano Ribeiro.pdf
o ciclo do contato Jorge Ponciano Ribeiro.pdfo ciclo do contato Jorge Ponciano Ribeiro.pdf
o ciclo do contato Jorge Ponciano Ribeiro.pdf
 
A QUATRO MÃOS - MARILDA CASTANHA . pdf
A QUATRO MÃOS  -  MARILDA CASTANHA . pdfA QUATRO MÃOS  -  MARILDA CASTANHA . pdf
A QUATRO MÃOS - MARILDA CASTANHA . pdf
 
Slides Lição 05, Central Gospel, A Grande Tribulação, 1Tr24.pptx
Slides Lição 05, Central Gospel, A Grande Tribulação, 1Tr24.pptxSlides Lição 05, Central Gospel, A Grande Tribulação, 1Tr24.pptx
Slides Lição 05, Central Gospel, A Grande Tribulação, 1Tr24.pptx
 
PROVA - ESTUDO CONTEMPORÂNEO E TRANSVERSAL: COMUNICAÇÃO ASSERTIVA E INTERPESS...
PROVA - ESTUDO CONTEMPORÂNEO E TRANSVERSAL: COMUNICAÇÃO ASSERTIVA E INTERPESS...PROVA - ESTUDO CONTEMPORÂNEO E TRANSVERSAL: COMUNICAÇÃO ASSERTIVA E INTERPESS...
PROVA - ESTUDO CONTEMPORÂNEO E TRANSVERSAL: COMUNICAÇÃO ASSERTIVA E INTERPESS...
 
PRÉDIOS HISTÓRICOS DE ASSARÉ Prof. Francisco Leite.pdf
PRÉDIOS HISTÓRICOS DE ASSARÉ Prof. Francisco Leite.pdfPRÉDIOS HISTÓRICOS DE ASSARÉ Prof. Francisco Leite.pdf
PRÉDIOS HISTÓRICOS DE ASSARÉ Prof. Francisco Leite.pdf
 
SLIDE DE Revolução Mexicana 1910 da disciplina cultura espanhola
SLIDE DE Revolução Mexicana 1910 da disciplina cultura espanholaSLIDE DE Revolução Mexicana 1910 da disciplina cultura espanhola
SLIDE DE Revolução Mexicana 1910 da disciplina cultura espanhola
 

Implementação de Lista Duplamente Encadeada (LDE) em C

  • 1. 1 #include <stdio.h> 2 #include <stdlib.h> 3 #include <locale.h> 4 #include <conio.h> 5 6 /* DEFININDO A ESTRUTURA DE NÓ */ 7 struct NO 8 { 9 int num; 10 struct NO *ant; 11 struct NO *prox; 12 }; 13 typedef struct NO no; 14 15 /* VARIÁVEIS GLOBAIS */ 16 int tam, x; 17 18 19 /* PROTÓTIPOS DE FUNÇÕES*/ 20 21 //FUNÇÕES PARA INICIALIZAR A LISTA 22 void inicia(no *LISTA); 23 24 //FUNÇÕES PARA CRIAR O MENU DO PROGRAMA 25 int menuPrincipal(void); 26 int menuAtualizar(void); 27 int menuBasico(void); 28 int menuRemover(void); 29 int menuInserir(void); 30 int menuPesquisar(void); 31 32 //FUNÇÕES PARA ESCOLHA DA OPÇÃO 33 void opcaoPrincipal(no *LISTA, int op); 34 void opcaoAtualizar(no *LISTA, int op); 35 void opcaoBasico(no *LISTA, int op); 36 void opcaoRemover(no *LISTA, int op); 37 void opcaoInserir(no *LISTA, int op); 38 void opcaoPesquisar(no *LISTA, int op); 39 40 //FUNÇÕES PARA INSERIR NA LISTA 41 no *insereFim(no *LISTA); 42 no *insereInicio(no *LISTA); 43 void insereEmOrdemCrescente(no *LISTA); 44 void insereEmOrdemDecrescente(no *LISTA); 45 void insereAnterior(no *LISTA); 46 void inserePosterior(no *LISTA); 47 48 //FUNÇÕES PARA IMPRIMIR A LISTA 49 void imprimirAnterior(no *LISTA); 50 void imprimirPosterior(no *LISTA); 51 52 //FUNÇÕES PARA LIBERAR A LISTA 53 void libera(no *LISTA); 54 55 //FUNÇÕES PARA REMOVER DA LISTA 56 no *removeInicio(no *LISTA); 57 no *removeFim(no *LISTA); 58 void removeEmOrdem(no *LISTA); 59 void removerAny(no *LISTA); 60 void removeAnterior(no *LISTA); 61 void removePosterior(no *LISTA); 62 63 //FUNÇÕES PARA PESQUISAR NÓS 64 no *buscar(no *LISTA); 65 int pesquisaMaior(no *LISTA); 66 int pesquisaMenor(no *LISTA); 67 void noAnterior(no *LISTA); 68 void noPosterior(no *LISTA); 69 70 //FUNÇÕES PARA ATUALIZAR O VALOR DE UM NÓ 71 void atualizar(no *LISTA); 72 void atualizarAnterior(no *LISTA); 73 void atualizarPosterior(no *LISTA); 74 75 //OUTRAS FUNÇÕES 76 no *inicio(no *LISTA); 77 no *fim(no *LISTA); 78 no *unico(no *LISTA); 79 80 /* PROGRAMA PRINCIPAL */ 81 int main(void) 82 { 83 setlocale(LC_ALL, "Portuguese"); 84 no *LISTA = (no *) malloc(sizeof(no));
  • 2. 85 if(!LISTA) 86 { 87 printf("nSem memória disponível!n"); 88 exit(1); 89 } 90 else 91 { 92 inicia(LISTA); 93 int opt; 94 95 do 96 { 97 system("cls"); 98 opt = menuPrincipal(); 99 opcaoPrincipal(LISTA, opt); 100 } 101 while(opt); 102 free(LISTA); 103 return 0; 104 } 105 } 106 107 /* IMPLEMENTAÇÃO DAS FUNÇÕES */ 108 109 //FUNÇÃO PARA INICIALIZAR A LISTA 110 void inicia(no *LISTA) 111 { 112 //LISTA->num = 0; 113 LISTA->ant = NULL; 114 LISTA->prox = NULL; 115 tam = 0; 116 } 117 118 //FUNÇÃO PARA CRIAR O MENU PRINCIPAL 119 int menuPrincipal(void) 120 { 121 system("cls"); 122 int op; 123 printf("n|================================================================|n"); 124 printf("n| MENU PRINCIPAL |"); 125 printf("n| 0. SAIR DO PROGRAMA. |"); 126 printf("n| 1. Funções Básicas. |"); 127 printf("n| 2. Funções para Inserir nós na L.D.E. |"); 128 printf("n| 3. Funções para Excluir nós da L.E.E. |"); 129 printf("n| 4. Funções para Pesquisar nós da L.D.E. |"); 130 printf("n| 5. Funções para Atualizar nós da L.D.E. |"); 131 printf("n|Digite a opção desejada: t"); 132 scanf("%d%*c", &op); 133 return op; 134 } 135 136 //FUNÇÃO PARA CRIAR O MENU DE FUNÇÕES BÁSICAS 137 int menuBasico(void) 138 { 139 system("cls"); 140 int op; 141 printf("nn|================================================================|n"); 142 printf("n| MENU FUNÇÕES BÁSICAS |n"); 143 printf("n| 0. Sair. |n"); 144 printf("n| 1. Zerar lista. |n"); 145 printf("n| 2. Quantidade de NÓS da lista. |n"); 146 printf("n| 3. Imprimir pelo ponteiro anterior. |n"); 147 printf("n| 4. Imprimir pelo ponteiro posterior. |n"); 148 printf("n| 5. Obter o nó do inicio da Lista. |n"); 149 printf("n| 6. Obter o nó do fim da Lista. |n"); 150 printf("n| 7. Verificar se o NÓ é o único da Lista. |n"); 151 printf("n|Digite a opção desejada: t"); 152 scanf("%d%*c", &op); 153 return op; 154 } 155 156 //FUNÇÃO PARA CRIAR O MENU DE FUNÇÕES PARA INSERÇÃO 157 int menuInserir(void) 158 { 159 system("cls"); 160 int op; 161 printf("n|----------------------------------------------------------------|n"); 162 printf("n| MENU FUNÇÕES INSERÇÃO |n"); 163 printf("n| 0. Sair. |n"); 164 printf("n| 1. Inserir no Inicio. |n"); 165 printf("n| 2. Inserir no Fim. |n"); 166 printf("n| 3. Inserir Antes de um Nó. |n"); 167 printf("n| 4. Inserir Depois de um Nó. |n"); 168 printf("n| 5. Inserir em Ordem Crescente. |n");
  • 3. 169 printf("n| 6. Inserir em Ordem DeCrescente. |n"); 170 printf("n| 7. Inserir em Qualquer Lugar. |n"); 171 printf("n|Digite a opção desejada: t"); 172 scanf("%d%*c", &op); 173 return op; 174 } 175 176 //FUNÇÃO PARA CRIAR O MENU DE FUNÇÕES PARA REMOÇÃO 177 int menuRemover(void) 178 { 179 system("cls"); 180 int op; 181 printf("n|----------------------------------------------------------------|n"); 182 printf("n| MENU FUNÇÕES REMOÇÃO |n"); 183 printf("n| 0. Sair. |n"); 184 printf("n| 1. Remover do Inicio. |n"); 185 printf("n| 2. Remover do Fim. |n"); 186 printf("n| 3. Remover Antes de um Nó. |n"); 187 printf("n| 4. Remover Depois de um Nó. |n"); 188 printf("n| 5. Remover de qualquer lugar. |n"); 189 printf("n|Digite a opção desejada: t"); 190 scanf("%d%*c", &op); 191 return op; 192 } 193 194 //FUNÇÃO PARA CRIAR O MENU DE FUNÇÕES PARA PESQUISAR NÓS NA LISTA 195 int menuPesquisar(void) 196 { 197 system("cls"); 198 int op; 199 printf("n|----------------------------------------------------------------|n"); 200 printf("n| MENU FUNÇÕES PESQUISA |n"); 201 printf("n| 0. Sair. |n"); 202 printf("n| 1. Buscar um Nó. |n"); 203 printf("n| 2. Encontrar o Maior elemento da lista. |n"); 204 printf("n| 3. Encontrar o Menor elemento da lista. |n"); 205 printf("n| 4. Nó Anterior a um Nó específico. |n"); 206 printf("n| 5. Nó Posterior a um Nó específico. |n"); 207 printf("n|Digite a opção desejada: t"); 208 scanf("%d%*c", &op); 209 return op; 210 } 211 212 //FUNÇÃO PARA CRIAR O MENU DE FUNÇÕES PARA ATUALIZAR UM NÓ ESPECÍFICO DA LISTA 213 int menuAtualizar(void) 214 { 215 system("cls"); 216 int op; 217 printf("n|----------------------------------------------------------------|n"); 218 printf("n| MENU FUNÇÕES ATUALIZAR |n"); 219 printf("n| 0. Sair. |n"); 220 printf("n| 1. Atualizar um Nó. |n"); 221 printf("n| 2. Atualizar um Nó Anterior a outro. |n"); 222 printf("n| 3. Atualizar um Nó Posterior a outro. |n"); 223 printf("n|Digite a opção desejada: t"); 224 scanf("%d%*c", &op); 225 return op; 226 } 227 228 void opcaoPrincipal(no *LISTA, int op) 229 { 230 int opcao; 231 switch(op) 232 { 233 case 0: 234 printf("n SAINDO! nn"); 235 libera(LISTA); 236 break; 237 238 case 1: 239 printf("nFUNÇÕES BÁSICASnn"); 240 do 241 { 242 opcao = menuBasico(); 243 opcaoBasico(LISTA, opcao); 244 getchar(); 245 } 246 while(opcao); 247 break; 248 249 case 2: 250 printf("nFUNÇÕES PARA INSERÇÃOnn"); 251 do 252 {
  • 4. 253 opcao = menuInserir(); 254 opcaoInserir(LISTA , opcao); 255 getchar(); 256 } 257 while(opcao); 258 break; 259 260 case 3: 261 printf("nFUNÇÕES PARA REMOÇÃOnn"); 262 do 263 { 264 opcao = menuRemover(); 265 opcaoRemover(LISTA , opcao); 266 getchar(); 267 } 268 while(opcao); 269 break; 270 271 case 4: 272 printf("nFUNÇÕES PARA PESQUISARnn"); 273 do 274 { 275 opcao = menuPesquisar(); 276 opcaoPesquisar(LISTA , opcao); 277 getchar(); 278 } 279 while(opcao); 280 break; 281 282 case 5: 283 printf("nFUNÇÕES PARA ATUALIZARnn"); 284 do 285 { 286 opcao = menuAtualizar(); 287 opcaoAtualizar(LISTA , opcao); 288 getchar(); 289 } 290 while(opcao); 291 break; 292 293 default: 294 printf("nComando inválido!nn"); 295 } 296 } 297 298 void opcaoBasico(no *LISTA , int op) 299 { 300 no *tmp; 301 switch(op) 302 { 303 case 0: 304 printf("n Aperte 0 (zero) novamente para voltar ao programa principal!nn"); 305 break; 306 307 case 1: 308 printf("nZERANDO A LISTA"); 309 libera(LISTA ); 310 inicia(LISTA ); 311 printf("nLista Zerada!nn"); 312 break; 313 314 case 2: 315 printf("nQUANTIDADE TOTAL DE NÓS DA LISTA"); 316 if(vazia(LISTA )) 317 printf("nA lista está vazia!nn"); 318 else 319 printf("nA quantidade total de NÓS desta lista é: %d.nn", tam); 320 break; 321 322 case 3: 323 printf("nIMPRIMINDO OS NÓS DA LISTA - PONTEIRO ANTERIOR"); 324 if(vazia(LISTA )) 325 printf("nA lista está vazia!nn"); 326 else 327 imprimirAnterior(LISTA ); 328 break; 329 330 case 4: 331 printf("nIMPRIMINDO OS NÓS DA LISTA - PONTEIRO POSTERIOR"); 332 if(vazia(LISTA )) 333 printf("nA lista está vazia!nn"); 334 else 335 imprimirPosterior(LISTA ); 336 break;
  • 5. 337 338 case 5: 339 printf("nPRIMEIRO NÓ DA LISTA"); 340 if(vazia(LISTA)) 341 printf("nA lista está vazia!nn"); 342 else 343 { 344 tmp = inicio(LISTA); 345 printf("nO nó do inicio da lista é: %3d. nn", tmp->num); 346 getchar(); 347 } 348 break; 349 350 case 6: 351 printf("nÚLTIMO NÓ DA LISTA"); 352 if(vazia(LISTA)) 353 printf("nA lista está vazia!nn"); 354 else 355 { 356 tmp = fim(LISTA); 357 printf("nO nó do fim da lista é: %3d. nn", tmp->num); 358 getchar(); 359 } 360 break; 361 362 case 7: 363 printf("ÚNICO NÓ DA LISTA"); 364 if(vazia(LISTA)) 365 printf("nA lista está vazia!nn"); 366 else 367 { 368 tmp = unico(LISTA); 369 if(tmp == NULL) 370 { 371 printf("n O nó não é o único da lista."); 372 } 373 else 374 { 375 printf("nO nó é o único da lista."); 376 } 377 getchar(); 378 } 379 break; 380 381 default: 382 printf("nComando inválido!nn"); 383 } 384 } 385 386 void opcaoInserir(no *LISTA, int op) 387 { 388 no *tmp; 389 switch(op) 390 { 391 case 0: 392 printf("n Aperte 0 (zero) novamente para voltar ao programa principal!nn"); 393 break; 394 395 case 1: 396 printf("nINSERINDO UM NOVO NÓ NO INICIO DA LISTA"); 397 tmp = insereInicio(LISTA); 398 printf("nNó inserido com sucesso: %3d. nn", tmp->num); 399 getchar(); 400 break; 401 402 case 2: 403 printf("nINSERINDO UM NOVO NÓ NO FIM DA LISTA"); 404 tmp = insereFim(LISTA); 405 printf("nNó inserido com sucesso: %3d. nn", tmp->num); 406 getchar(); 407 break; 408 409 case 3: 410 printf("n INSERINDO UM NOVO NÓ ANTERIOR A OUTRO"); 411 insereAnterior(LISTA); 412 printf("nNó inserido com sucesso: %3d. nn", tmp->num); 413 getchar(); 414 break; 415 416 case 4: 417 printf("n INSERINDO UM NOVO NÓ POSTERIOR A OUTRO"); 418 inserePosterior(LISTA); 419 break; 420
  • 6. 421 case 5: 422 printf("n INSERINDO UM NOVO NÓ EM ORDEM CRESCENTE"); 423 insereEmOrdemCrescente(LISTA); 424 break; 425 426 case 6: 427 printf("n INSERINDO UM NOVO NÓ EM ORDEM DECRESCENTE"); 428 insereEmOrdemDecrescente(LISTA); 429 break; 430 431 default: 432 printf("nComando inválido!nn"); 433 } 434 } 435 436 void opcaoRemover(no *LISTA, int op) 437 { 438 no * tmp; 439 switch(op) 440 { 441 case 0: 442 printf("n Aperte 0 (zero) novamente para voltar ao programa principal!nn"); 443 break; 444 445 case 1: 446 printf("nRETIRANDO UM ELEMENTO DO INICIO DA LISTA"); 447 if(vazia(LISTA)) 448 printf("nA lista está vazia!nn"); 449 else 450 { 451 tmp = removeInicio(LISTA); 452 printf("nRetirado: %3d. nn", tmp->num); 453 getchar(); 454 } 455 break; 456 457 case 2: 458 printf("nRETIRANDO UM ELEMENTO DO FIM DA LISTA"); 459 if(vazia(LISTA)) 460 { 461 printf("nA lista está vazia! nn"); 462 } 463 else 464 { 465 tmp = removeFim(LISTA); 466 printf("nRetirado: %3d. nn", tmp->num); 467 getchar(); 468 } 469 break; 470 471 case 3: 472 printf("nRETIRANDO UM ELEMENTO ANTERIOR A OUTRO"); 473 if(vazia(LISTA)) 474 { 475 printf("nA lista está vazia! nn"); 476 } 477 else 478 { 479 removeAnterior(LISTA); 480 } 481 getchar(); 482 break; 483 484 case 4: 485 printf("nRETIRANDO UM ELEMENTO POSTERIOR A OUTRO"); 486 if(vazia(LISTA)) 487 { 488 printf("nA lista está vazia! nn"); 489 } 490 else 491 { 492 removePosterior(LISTA); 493 } 494 getchar(); 495 break; 496 497 case 5: 498 printf("nRETIRANDO UM ELEMENTO DE QUALQUER LUGAR DA LISTA"); 499 if(vazia(LISTA)) 500 { 501 printf("nA lista está vazia! nn"); 502 } 503 else 504 {
  • 7. 505 removerAny(LISTA); 506 } 507 getchar(); 508 break; 509 510 default: 511 printf("nComando inválido! nn"); 512 } 513 } 514 515 void opcaoPesquisar(no *LISTA, int op) 516 { 517 no *tmp; 518 int res; 519 switch(op) 520 { 521 case 0: 522 printf("n Aperte 0 (zero) novamente para voltar ao programa principal!nn"); 523 break; 524 525 case 1: 526 printf("nBUSCANDO UM NÓ nn"); 527 if(vazia(LISTA)) 528 printf("nA lista está vazia! nn"); 529 else 530 { 531 tmp = buscar(LISTA); 532 if(tmp == NULL) 533 printf("nO valor NÃO foi encontradonn"); 534 else 535 { 536 printf("nO valor foi encontrado: %d nn", tmp->num); 537 } 538 } 539 getchar(); 540 break; 541 542 case 2: 543 printf("nPESQUISANDO O MAIOR ELEMENTO DA LISTA"); 544 if(vazia(LISTA)) 545 printf("nA lista está vazia! nn"); 546 else 547 { 548 res = pesquisaMaior(LISTA); 549 printf("nO maior elemento da lista é: %d. nn", res); 550 getchar(); 551 } 552 break; 553 554 case 3: 555 printf("nPESQUISANDO O MENOR ELEMENTO DA LISTA"); 556 if(vazia(LISTA)) 557 printf("nA lista está vazia! nn"); 558 else 559 { 560 res = pesquisaMenor(LISTA); 561 printf("nO menor elemento da lista é: %d. nn", res); 562 getchar(); 563 } 564 break; 565 566 case 4: 567 printf("nOBTENDO O VALOR DO NÓ ANTERIOR"); 568 if(vazia(LISTA)) 569 printf("nA lista está vazia! nn"); 570 else 571 noAnterior(LISTA); 572 getchar(); 573 break; 574 575 case 5: 576 printf("nOBTENDO O VALOR DO NÓ POSTERIOR"); 577 if(vazia(LISTA)) 578 printf("nA lista está vazia! nn"); 579 else 580 noPosterior(LISTA); 581 getchar(); 582 break; 583 584 default: 585 printf("nComando inválido! nn"); 586 } 587 } 588
  • 8. 589 void opcaoAtualizar(no *LISTA, int op) 590 { 591 switch(op) 592 { 593 case 0: 594 printf("n Aperte 0 (zero) novamente para voltar ao programa principal!nn"); 595 break; 596 597 case 1: 598 printf("nATUALIZANDO UM VALOR DE UM NÓ DA LISTA"); 599 if(vazia(LISTA)) 600 printf("nA lista está vazia! nn"); 601 else 602 atualizar(LISTA); 603 getchar(); 604 break; 605 606 case 2: 607 printf("nATUALIZANDO UM NÓ ANTERIOR A OUTRO"); 608 if(vazia(LISTA)) 609 printf("nA lista está vazia! nn"); 610 else 611 atualizarAnterior(LISTA); 612 getchar(); 613 break; 614 615 case 3: 616 printf("nATUALIZANDO UM NÓ POSTERIOR A OUTRO"); 617 if(vazia(LISTA)) 618 printf("nA lista está vazia! nn"); 619 else 620 atualizarPosterior(LISTA); 621 getchar(); 622 break; 623 624 default: 625 printf("nComando inválido! nn"); 626 } 627 } 628 629 /* FUNÇÃO PARA VERIFICAR SE A LISTA ESTÁ VAZIA */ 630 int vazia(no *LISTA) 631 { 632 if((LISTA->prox==NULL)&&(LISTA->ant==NULL)) 633 { 634 return 1; 635 } 636 else 637 return 0; 638 } 639 640 /* FUNÇÃO PARA ALOCAR UM NOVO NÓ */ 641 no *aloca() 642 { 643 no *novo=(no *) malloc(sizeof(no)); 644 if(!novo) 645 { 646 printf("nSem memória disponível! n"); 647 exit(1); 648 } 649 else 650 { 651 novo->ant = NULL; 652 novo->prox = NULL; 653 printf("nNovo nó: "); 654 scanf("%d", &novo->num); 655 return novo; 656 } 657 } 658 659 /* ====================================================================== 660 FUNÇÕES PARA INSERIR */ 661 662 /* FUNÇÃO PARA INSERIR NO FIM DA LISTA */ 663 no *insereFim(no *LISTA) 664 { 665 no *novo = aloca(); 666 667 if(vazia(LISTA)) 668 { 669 LISTA->prox = novo; 670 novo->ant = LISTA; 671 } 672 else
  • 9. 673 { 674 no *aux = LISTA->prox; 675 while(aux->prox != NULL) 676 aux = aux->prox; 677 novo->ant = aux; 678 aux->prox = novo; 679 novo->prox = NULL; 680 } 681 tam++; 682 return novo; 683 } 684 685 /* FUNÇÃO PARA INSERIR NO INICIO DA LISTA */ 686 no *insereInicio(no *LISTA) 687 { 688 no *novo = aloca(); 689 if(vazia(LISTA)) 690 { 691 LISTA->prox = novo; 692 novo->ant = LISTA; 693 } else { 694 no *aux = LISTA->prox; 695 LISTA->prox = novo; 696 aux->ant = novo; 697 novo->ant = LISTA; 698 novo->prox = aux; 699 } 700 tam++; 701 return novo; 702 } 703 704 /* FUNÇÃO PARA INSERIR ANTES DE UM NÓ ESPECÍFICO DA LISTA */ 705 void insereAnterior(no *LISTA) 706 { 707 printf("nDigite um valor a ser procurado: "); 708 scanf("%d", &x); 709 no *aux1, *aux2, *aux3; 710 while((LISTA != NULL) && (LISTA->num != x)) 711 { 712 aux1 = LISTA; 713 aux2 = LISTA->ant; 714 LISTA = LISTA->prox; 715 aux3 = aux1->ant; 716 } 717 no *novo = aloca(); 718 tam++; 719 printf("nInserido %3d. n", novo->num); 720 } 721 722 /* FUNÇÃO PARA INSERIR DEPOIS DE UM NÓ ESPECÍFICO DA LISTA */ 723 void inserePosterior(no *LISTA) 724 { 725 printf("nDigite um valor a ser procurado: "); 726 scanf("%d", &x); 727 no *aux1 = LISTA, *aux2, *aux3; 728 while((aux1 != NULL) && (aux1->num != x)) 729 { 730 aux1 = aux1->prox; 731 aux2 = aux1->prox; 732 aux3 = aux2->prox; 733 } 734 no *novo = aloca(); 735 printf("nInserido: %3d. n", novo->num); 736 tam++; 737 } 738 739 /* FUNÇÃO PARA INSERIR EM ORDEM CRESCENTE */ 740 void insereEmOrdemCrescente(no *LISTA) 741 { 742 printf("n implementar "); 743 744 } 745 746 /* FUNÇÃO PARA INSERIR EM ORDEM DECRESCENTE */ 747 void insereEmOrdemDecrescente(no *LISTA) 748 { 749 printf("n implementar "); 750 751 } 752 753 /* =============================================================== 754 FUNÇÕES PARA IMPRIMIR NÓS DA LISTA */ 755 756 /* FUNÇÃO PARA IMPRIMIR OS ELEMENTOS DE UMA LISTA - PONTEIRO ANTERIOR */
  • 10. 757 void imprimirAnterior(no *LISTA) 758 { 759 printf("n implementar "); 760 } 761 762 /* FUNÇÃO PARA IMPRIMIR OS ELEMENTOS DE UMA LISTA - PONTEIRO POSTERIOR */ 763 void imprimirPosterior(no *LISTA) 764 { 765 no *tmp; 766 tmp = LISTA-> prox ; 767 printf("nLista:"); 768 while( tmp != NULL) 769 { 770 printf("%5d", tmp-> num); 771 tmp = tmp-> prox ; 772 } 773 printf("n "); 774 int count; 775 for(count= 0 ; count < tam ; count++) 776 printf(" ^ "); 777 printf("nOrdem:"); 778 for(count= 0 ; count < tam ; count++) 779 printf("%5d", count+1); 780 printf("nn"); 781 } 782 783 /* FUNÇÃO PARA LIBERAR A LISTA */ 784 void libera(no *LISTA) 785 { 786 if(!vazia(LISTA)) 787 { 788 no *proxNo, *atual, *antNo; 789 atual = LISTA; 790 while(atual!= NULL) 791 { 792 proxNo = atual-> prox ; 793 antNo = atual-> ant; 794 free(atual); 795 atual = proxNo; 796 } 797 } 798 } 799 800 801 /* =============================================================== 802 FUNÇÕES PARA REMOVER NÓS*/ 803 804 /* FUNÇÃO PARA REMOVER NÓS DO INICIO DA LISTA */ 805 no *removeInicio(no *LISTA) 806 { 807 no *aux = LISTA-> prox ; 808 LISTA-> prox = aux-> prox ; 809 LISTA-> ant = NULL; 810 tam--; 811 return aux; 812 } 813 814 /* FUNÇÃO PARA REMOVER NÓS DO FIM DA LISTA */ 815 no *removeFim(no *LISTA) 816 { 817 no *ultimo = LISTA-> prox , *penultimo = LISTA; 818 while(ultimo-> prox != NULL) 819 { 820 penultimo = ultimo; 821 ultimo = ultimo-> prox ; 822 } 823 penultimo-> prox = NULL; 824 penultimo-> ant = NULL; 825 tam--; 826 return ultimo; 827 } 828 829 /* FUNÇÃO PARA REMOVER UM NÓ ANTES DE OUTRO NÓ ESPECÍFICO */ 830 void removeAnterior(no *LISTA) 831 { 832 printf("n implementar "); 833 } 834 835 /* FUNÇÃO PARA REMOVER UM NÓ DEPOIS DE OUTRO NÓ ESPECÍFICO */ 836 void removePosterior(no *LISTA) 837 { 838 printf("nDigite um valor a ser procurado: "); 839 scanf("%d", &x); 840 no *aux1 = LISTA-> prox , *aux2 = LISTA, *aux3;
  • 11. 841 if((aux1->ant==NULL)&&(aux1->prox==NULL)) 842 { 843 printf("n ÚNICO elemento da lista, não há posterior!"); 844 } 845 else 846 { 847 while((aux1->prox != NULL) && (aux1->num != x)) 848 { 849 printf("n dentro do while"); 850 aux2 = aux1; 851 aux1 = aux1->prox; 852 aux2 = aux1->prox; 853 aux3 = aux2->prox; 854 } 855 printf("n AUX1 %d t AUX2 %d t AUX3 %d t", aux1->num, aux2->num, aux3->num); 856 printf("nRetirado: %3d. n", aux2->num); 857 aux1->prox = aux3; 858 aux3->ant = aux1; 859 aux2->ant = NULL; 860 aux2->prox = NULL; 861 tam--; 862 } 863 } 864 865 /* FUNÇÃO PARA REMOVER UM NÓ DE QUALQUER PARTE DA LISTA */ 866 void removerAny(no *LISTA) 867 { 868 int opt,count; 869 printf("nQue posicao, [de 1 ate %d] voce deseja retirar: ", tam); 870 scanf("%d", &opt); 871 872 if(opt>0 && opt <= tam) 873 { 874 if(opt==1) 875 return removeInicio(LISTA); 876 else 877 { 878 no *atual = LISTA->prox, *anterior = LISTA; 879 for(count=1 ; count < opt ; count++) 880 { 881 anterior = atual; 882 atual = atual->prox; 883 } 884 anterior->prox = atual->prox; 885 tam--; 886 return atual; 887 } 888 printf("n Elemento removido com sucesso!! n"); 889 } 890 else 891 { 892 printf("n Elemento inválido! n"); 893 return NULL; 894 } 895 } 896 897 /* =============================================================== 898 FUNÇÕES PARA BUSCAR E ATUALIZAR NÓS DA LISTA */ 899 900 /* FUNÇÃO PARA BUSCAR UM NÓ ESPECÍFICO */ 901 no *buscar(no *LISTA) 902 { 903 printf("nDigite um valor a ser procurado: "); 904 scanf("%d", &x); 905 no *aux = LISTA->prox; 906 while((aux != NULL) && (aux->num != x) ) 907 { 908 aux = aux->prox; 909 } 910 return aux; 911 } 912 913 /* FUNÇÃO PARA BUSCAR UM NÓ ANTERIOR A OUTRO */ 914 void noAnterior(no *LISTA) 915 { 916 no *aux = buscar(LISTA); 917 if(aux == NULL) 918 { 919 printf("n O valor NÃO foi encontrado. n"); 920 } 921 else 922 { 923 printf("n O valor foi encontrado: %d n", aux->num); 924 if(aux->ant==NULL)
  • 12. 925 { 926 printf("n Não existe nó anterior pois este é o primeiro nó da lista"); 927 } 928 else 929 { 930 no *aux2 = aux->ant; 931 printf("n O nó anterior a este é: %d", aux2->num); 932 } 933 } 934 } 935 936 /* FUNÇÃO PARA BUSCAR UM NÓ POSTERIOR A OUTRO */ 937 void noPosterior(no *LISTA) 938 { 939 no *aux = buscar(LISTA); 940 if(aux == NULL) 941 { 942 printf("n O valor NÃO foi encontrado. n"); 943 } 944 else 945 { 946 printf("n O valor foi encontrado: %d n", aux->num); 947 if(aux->prox==NULL) 948 { 949 printf("n Não existe nó posterior pois este é o primeiro nó da lista"); 950 } 951 else 952 { 953 no *aux2 = aux->prox; 954 printf("n O nó posterior a este é: %d", aux2->num); 955 } 956 } 957 } 958 959 /* FUNÇÃO PARA ATUALIZAR UM NÓ ESPECÍFICO */ 960 void atualizar(no *LISTA) 961 { 962 no *aux = buscar(LISTA); 963 if(aux == NULL) 964 { 965 printf("n O valor NÃO foi encontrado. n"); 966 } 967 else 968 { 969 printf("n O valor foi encontrado: %d n", aux->num); 970 printf("n Digite o novo valor: "); 971 scanf("%d", &aux->num); 972 printf("n O valor foi atualizado com sucesso! nn"); 973 } 974 } 975 976 /* FUNÇÃO PARA ATUALIZAR UM NÓ POSTERIOR A OUTRO */ 977 void atualizarPosterior(no *LISTA) 978 { 979 printf("n implementar "); 980 } 981 982 /* FUNÇÃO PARA ATUALIZAR UM NÓ ANTERIOR A OUTRO NÓ */ 983 void atualizarAnterior(no *LISTA) 984 { 985 printf("n implementar "); 986 } 987 988 /* FUNÇÃO PARA PESQUISAR O MAIOR VALOR DA LISTA */ 989 int pesquisaMaior(no *LISTA) 990 { 991 int maior = LISTA->num; 992 while(LISTA != NULL) 993 { 994 if(LISTA->num > maior) 995 maior = LISTA->num; 996 LISTA = LISTA->prox; 997 } 998 return maior; 999 } 1000 1001 /* FUNÇÃO PARA PESQUISAR O MENOR VALOR DA LISTA */ 1002 int pesquisaMenor(no *LISTA) 1003 { 1004 LISTA = LISTA->prox; 1005 int menor = LISTA->num; 1006 while(LISTA != NULL) 1007 { 1008 if(LISTA->num < menor)
  • 13. 1009 menor = LISTA->num; 1010 LISTA = LISTA->prox; 1011 } 1012 return menor; 1013 } 1014 1015 no *fim(no *LISTA) 1016 { 1017 no *aux1 = LISTA->prox, *aux2 = LISTA; 1018 1019 if((aux1->ant == NULL) && (aux1->prox == NULL)) 1020 { 1021 return aux1; 1022 } 1023 else 1024 { 1025 while(aux1->prox != NULL) 1026 { 1027 aux1 = aux1->prox; 1028 } 1029 aux2 = aux1; 1030 return aux2; 1031 } 1032 } 1033 1034 no *inicio(no *LISTA) 1035 { 1036 no *aux = LISTA->prox++; 1037 return aux; 1038 } 1039 1040 //VERIFICANDO SE O NÓ É O ÚNICO DA LISTA 1041 no *unico(no *LISTA) 1042 { 1043 no *aux = LISTA; 1044 if((aux->ant == NULL) && (aux->prox == NULL)) 1045 { 1046 return aux; 1047 } 1048 else 1049 { 1050 return NULL; 1051 } 1052 } 1053