Ir ao conteúdo
  • Cadastre-se

jcgs98

Membro Pleno
  • Posts

    90
  • Cadastrado em

  • Última visita

Tudo que jcgs98 postou

  1. void decimalParaBinario(int i) { if (i > 1) { decimalParaBinario(i / 2); if (i) printf("%d", i % 2); } if ((i == 1) || (!i)) printf("%d", i); }
  2. void remRepListaOrd(TLista *L2,TLista *U2) { TLista L=*L2, U=*U2; if ((!L)||(!L->prox)) return; remover (&L->prox, &U,L->valor); remRepListaOrd(&L->prox,&U); } uso a função de remover a partir do próximo da lista. @devair1010 Não deve ter rodado por causa dessa forma de "escrever": (*U)?novo->ant=*U,(*U)->prox=novo,*U=novo:*L = novo; Tenta mudar. Por exemplo, (*U)?novo->ant=*U,(*U)->prox=novo,*U=novo:*L = novo; é igual a: if (*U) { novo->ant=*U; (*U)->prox=novo; *U=novo; } else *L = novo; #include <stdio.h> #include <stdlib.h> typedef struct No { int valor; struct No *prox, *ant; } TNo; typedef TNo* TLista; int inserir (TLista *L, TLista *U, int num); int remover (TLista *L, TLista *U,int numero); int alterar (TLista L, int velho, int novo); TLista pesquisar (TLista L, int num); void exibir (TLista L); void exibirAoContrario (TLista U); void clonar (TLista *L, TLista L2); int inserirNaPosicao (TLista *L, TLista *U, int posicao, int numero); int menu (TLista L, TLista L2); int tamanho (TLista L); void insereFim(TLista *L, TLista *U, int numero); void botarCrescente(TLista *L); void inverterLista (TLista *L,TLista *U); float media(TLista L2); int pesquisaMaior(TLista L2); int pesquisaMenor(TLista L2); float somaDosElementos(TLista L2); void remRepListaOrd(TLista *L, TLista *U); int main () { TLista L=NULL, L2=NULL, U=NULL, pos; int num1, num2, op; do { system ("cls"); op = menu (L, L2); switch (op) { //INSERIR case 1: printf ("Entre com o número: "); scanf ("%d", &num1); (inserir (&L, &U, num1))?printf ("Inserção realizada!\n"):printf ("ERRO: Inserção não realizada!\n"); break; //REMOVER case 2: printf ("Entre com o número a ser removido: "); scanf ("%d", &num1); printf ((!remover (&L, &U, num1))?"ERRO: Remoção não realizada!\n":"Remoção realizada %i vezes!\n", remover (&L, &U, num1)); break; //ALTERAR case 3: printf ("Entre com o número a ser alterado: "); scanf ("%d", &num1); printf ("Entre com o novo número: "); scanf ("%d", &num2); printf ((alterar (L, num1, num2))?"Alteração realizada!\n":"ERRO: Alteração não realizada!\n"); break; //PESQUISAR case 4: printf ("Entre com o número a ser pesquisado: "); scanf ("%d", &num1); printf ((pesquisar (L, num1))?"O número foi encontrado na lista!\n":"ERRO: O número não se encontra na lista!\n"); break; //EXIBE NORMAL case 5: (!L)?printf("Lista vazia!\n"):printf("Lista: "),exibir (L),printf("\n"); break; //EXIBE INVERTIDO case 6: (!U)?printf("Lista vazia!\n"):printf("Lista: "),exibirAoContrario (U),printf("\n"); break; //CLONAR case 7: clonar (&L2,L); break; //INSERE NA POSIÇÃO case 8: printf ("Entre com o número a ser inserido: "); scanf ("%d", &num1); printf ("Entre com o posicao onde número >>%i<< vai ser inserido: ", num1); scanf ("%d", &num2); printf ((inserirNaPosicao (&L, &U, num2, num1))?"Insercao realizada!\n":"ERRO: Inserção não realizada!\n"); break; //INSERE NO FIM case 9: printf ("Entre com o número a ser inserido: "); scanf ("%d", &num1); insereFim(&L, &U, num1); break; //ORDENA CRESCENTE case 10:printf((!L)?"Lista vazia!\n":0),botarCrescente(&L); break; //remover repeticao case 11:remRepListaOrd(&L,&U); break; //INVERTER case 12:inverterLista (&L,&U); break; //fim case 0: printf ("Fim do programa!\n"); break; //erro default:printf ("Opção inválida!\nTente novamente!\n"); } system ("pause"); } while (op != 0); } int menu (TLista L, TLista L2) { int opcao; system ("cls"); printf ("\nTamanho da Lista: %i\n\n",tamanho (L)); printf ("Lista: ");exibir (L); printf ("|\n"); printf ("Clone: ");exibir (L2); printf ("|\n\n"); printf ("Menor elemento da lista......: %i. \n", pesquisaMenor(L)); printf ("Maior elemento da lista......: %i. \n", pesquisaMaior(L)); printf ("Media dos elementos da lista.: %.2f. \n\n", media(L)); printf ("Menu de opções:\n\n"); printf ("( 1)\tInserir\n( 2)\tRemover\n( 3)\tAlterar\n"); printf ("( 4)\tPesquisar\n( 5)\tExibir na Ordem Natural\n"); printf ("( 6)\tExibir na Ordem Inversa\n( 7)\tClonar\n"); printf ("( 8)\tInserir na Posicao\n( 9)\tInsere no Fim\n(10)\tOrdenar Lista\n"); printf ("(11)\tRemove Repeticoes da lista; printf ("(12)\tInverter Lista\n(13)\tComparar Listas(*FAZER)\n( 0)\tSair\n\n"); printf ("Entre Com a Opcao: "); scanf ("%d", &opcao); return opcao; } int inserir (TLista *L, TLista *U, int num) { TLista aux = (TLista) malloc (sizeof(TNo)); if (!aux) { return 0; } else { aux->valor = num; aux->prox = *L; aux->ant = NULL; if (*L) { (*L)->ant = aux; } else { *U = aux; } *L = aux; return 1; } } int remover (TLista *L, TLista *U,int numero) { TLista aux1, aux2, aux3; int cont; while ((*L) && ((*L)->valor == numero)) { aux2 = (*L)->ant; aux1 = (*L)->prox; free (*L); cont++; *L = aux1; (*L)?(*L)->ant = aux2:0; } if (!*L) { *U=NULL; } else { aux2 = *L; aux1 = (*L)->prox; while (aux1) { if (aux1->valor == numero) { aux3 = aux2; (*U==aux1)?*U=aux3:0; (aux1->prox)?aux1->prox->ant=aux2:0; aux2->prox = aux1->prox; free (aux1); cont++; aux1 = aux2->prox; } else { aux2 = aux1; aux1 = aux1->prox; } } } return cont; } int alterar (TLista L, int velho, int novo) { TLista aux = L; int c = 0; while (aux) { if (aux->valor == velho) { aux->valor = novo; c++; } aux = aux->prox; } return c; } TLista pesquisar (TLista L, int num) { if (L==NULL) return NULL; if (L->valor==num) return L; pesquisar (L->prox, num); } void exibir (TLista L2) { TLista L=L2; if(L) { printf ("%d ", L->valor); exibir (L->prox); } } void exibirAoContrario (TLista U2) { TLista U=U2; if(U) { printf ("%d ", U->valor); exibirAoContrario (U->ant); } } void clonar (TLista *L, TLista L2) { TLista L3=L2; TLista U; while(L3) { insereFim(&*L, &U, L3->valor); L3=L3->prox; } } int inserirNaPosicao (TLista *L, TLista *U, int posicao, int num) { int t=tamanho (*L), con=0; TLista aux2=*L, aux, novo; if(!posicao||posicao>t+1) { return 0; } if(posicao==1) { inserir (&*L, &*U, num); return 1; } if(posicao==t+1) { insereFim(&*L, &*U, num); return 1; } posicao=posicao-1; novo=(TLista) malloc (sizeof(TNo)); novo->valor=num; while (con<posicao-1) { aux2=aux2->prox; con++; } aux=aux2->prox; novo->ant=aux2; aux2->prox=novo; aux->ant=novo; novo->prox=aux; return 1; } void insereFim(TLista *L, TLista *U, int numero) { TLista novo=(TLista) malloc(sizeof(TNo)); novo->prox=NULL; novo->valor=numero; (*U)?novo->ant=*U,(*U)->prox=novo,*U=novo:*L = novo; *U = novo; } void botarCrescente(TLista *L) { TLista genesis = *L, ordenada; int gV,oV; while(genesis) { ordenada=genesis->prox; while(ordenada) { if(genesis->valor > ordenada->valor) { gV=genesis->valor; oV=ordenada->valor; ordenada->valor=gV; genesis->valor=oV; } ordenada = ordenada->prox; } genesis=genesis->prox; } } int tamanho (TLista L1) { TLista L=L1; if (!L) return 0; return (1+tamanho (L->prox)); } void inverterLista (TLista *L,TLista *U) { TLista aux=*L; *L=NULL; *U=NULL; while(aux) { inserir (&*L, &*U, aux->valor); aux=aux->prox; } } int pesquisaMaior(TLista L2) { TLista L=L2; if (!L) return 0; int maior = pesquisaMaior(L->prox); if (L->valor > maior) return L->valor; return maior; } int pesquisaMenor(TLista L2) { TLista L=L2; if (!L) return 0; int menor=L->valor; while(L) { if(L->valor < menor) { menor = L->valor; } L = L->prox; } return menor; } float media(TLista L2) { if (L2) return (somaDosElementos(L2)/tamanho(L2)); return 0; } float somaDosElementos(TLista L2) { TLista L=L2; if (!L) return 0; return L->valor + somaDosElementos(L->prox); } void remRepListaOrd(TLista *L2,TLista *U2) { TLista L=*L2, U=*U2; if ((!L)||(!L->prox)) return; remover (&L->prox, &U,L->valor); remRepListaOrd(&L->prox,&U); } FIZ A 11
  3. #include <stdio.h> #include <stdlib.h> typedef struct No{int valor;struct No *prox, *ant;}TNo;typedef TNo* TLista; int inserir (TLista *L, TLista *U, int num); int remover (TLista *L, TLista *U,int numero); int alterar (TLista L, int velho, int novo); TLista pesquisar (TLista L, int num); void exibir (TLista L); void exibirAoContrario (TLista U); void clonar (TLista *L, TLista L2); int inserirNaPosicao (TLista *L, TLista *U, int posicao, int numero); int menu (TLista L, TLista L2); int tamanho (TLista L); void insereFim(TLista *L, TLista *U, int numero); void botarCrescente(TLista *L); void inverterLista (TLista *L,TLista *U); float media(TLista L2); int pesquisaMaior(TLista L2); int pesquisaMenor(TLista L2); float somaDosElementos(TLista L2); void remRepListaOrd(TLista L); int main () { TLista L=NULL, L2=NULL, U=NULL, pos; int num1, num2, op; do { system ("cls"); op = menu (L, L2); switch (op) { //INSERIR case 1: printf ("Entre com o número: "); scanf ("%d", &num1); (inserir (&L, &U, num1))?printf ("Inserção realizada!\n"):printf ("ERRO: Inserção não realizada!\n"); break; //REMOVER case 2: printf ("Entre com o número a ser removido: "); scanf ("%d", &num1); printf ((!remover (&L, &U, num1))?"ERRO: Remoção não realizada!\n":"Remoção realizada %i vezes!\n", remover (&L, &U, num1)); break; //ALTERAR case 3: printf ("Entre com o número a ser alterado: "); scanf ("%d", &num1); printf ("Entre com o novo número: "); scanf ("%d", &num2); printf ((alterar (L, num1, num2))?"Alteração realizada!\n":"ERRO: Alteração não realizada!\n"); break; //PESQUISAR case 4: printf ("Entre com o número a ser pesquisado: "); scanf ("%d", &num1); printf ((pesquisar (L, num1))?"O número foi encontrado na lista!\n":"ERRO: O número não se encontra na lista!\n"); break; //EXIBE NORMAL case 5: (!L)?printf("Lista vazia!\n"):printf("Lista: "),exibir (L),printf("\n"); break; //EXIBE INVERTIDO case 6: (!U)?printf("Lista vazia!\n"):printf("Lista: "),exibirAoContrario (U),printf("\n"); break; //CLONAR case 7: clonar (&L2,L); break; //INSERE NA POSIÇÃO case 8: printf ("Entre com o número a ser inserido: "); scanf ("%d", &num1); printf ("Entre com o posicao onde número >>%i<< vai ser inserido: ", num1); scanf ("%d", &num2); printf ((inserirNaPosicao (&L, &U, num2, num1))?"Insercao realizada!\n":"ERRO: Inserção não realizada!\n"); break; //INSERE NO FIM case 9: printf ("Entre com o número a ser inserido: "); scanf ("%d", &num1); insereFim(&L, &U, num1); break; //ORDENA CRESCENTE case 10:printf((!L)?"Lista vazia!\n":0),botarCrescente(&L); break; //remover repeticao case 11:remRepListaOrd(L); break; //INVERTER case 12:inverterLista (&L,&U); break; //fim case 0: printf ("Fim do programa!\n"); break; //erro default:printf ("Opção inválida!\nTente novamente!\n"); } system ("pause"); } while (op != 0); } int menu (TLista L, TLista L2) { int opcao; system ("cls"); printf ("\nTamanho da Lista: %i\n\n",tamanho (L)); printf ("Lista: ");exibir (L); printf ("|\n"); printf ("Clone: ");exibir (L2); printf ("|\n\n"); printf ("Menor elemento da lista......: %i. \n", pesquisaMenor(L)); printf ("Maior elemento da lista......: %i. \n", pesquisaMaior(L)); printf ("Media dos elementos da lista.: %.2f. \n\n", media(L)); printf ("Menu de opções:\n\n"); printf ("(1)\tInserir\n(2)\tRemover\n(3)\tAlterar\n"); printf ("(4)\tPesquisar\n(5)\tExibir na Ordem Natural\n"); printf ("(6)\tExibir na Ordem Inversa\n(7)\tClonar\n"); printf ("(8)\tInserir na Posicao\n"); printf ("(9)\tInsere no Fim\n(10)\tOrdenar Lista\n"); printf ("(11)\tRemove Repeticoes da lista\n(*INCOMPLETA - so remove depois de ordenar)"); printf ("(12)\tInverter Lista\n"); printf ("(13)\tComparar Listas\n(*FAZER)"); printf ("(0)\tSair\n\n"); printf ("Entre Com a Opcao: "); scanf ("%d", &opcao); return opcao; } int inserir (TLista *L, TLista *U, int num) { TLista aux = (TLista) malloc (sizeof(TNo)); if (!aux) {return 0;} else { aux->valor = num; aux->prox = *L; aux->ant = NULL; if (*L) { (*L)->ant = aux; } else { *U = aux; } *L = aux; return 1; } } int remover (TLista *L, TLista *U,int numero) { TLista aux1, aux2, aux3; int cont; while ((*L) && ((*L)->valor == numero)) { aux2 = (*L)->ant; aux1 = (*L)->prox; free (*L); cont++; *L = aux1; (*L)?(*L)->ant = aux2:0; } if (!*L) { *U=NULL; } else { aux2 = *L; aux1 = (*L)->prox; while (aux1) { if (aux1->valor == numero) { aux3 = aux2; (*U==aux1)?*U=aux3:0; (aux1->prox)?aux1->prox->ant=aux2:0; aux2->prox = aux1->prox; free (aux1); cont++; aux1 = aux2->prox; } else { aux2 = aux1; aux1 = aux1->prox; } } } return cont; } int alterar (TLista L, int velho, int novo) { TLista aux = L; int c = 0; while (aux) { if (aux->valor == velho) { aux->valor = novo; c++; } aux = aux->prox; } return c; } TLista pesquisar (TLista L, int num) { if (L==NULL) return NULL; if (L->valor==num) return L; pesquisar (L->prox, num); } void exibir (TLista L2) { TLista L=L2; if(L) { printf ("%d ", L->valor); exibir (L->prox); } } void exibirAoContrario (TLista U2) { TLista U=U2; if(U) { printf ("%d ", U->valor); exibirAoContrario (U->ant); } } void clonar (TLista *L, TLista L2) { TLista L3=L2; TLista U; while(L3) { insereFim(&*L, &U, L3->valor); L3=L3->prox; } } int inserirNaPosicao (TLista *L, TLista *U, int posicao, int num) { int t=tamanho (*L), con=0; TLista aux2=*L, aux, novo; if(!posicao||posicao>t+1) { return 0; } if(posicao==1) { inserir (&*L, &*U, num); return 1; } if(posicao==t+1) { insereFim(&*L, &*U, num); return 1; } posicao=posicao-1; novo=(TLista) malloc (sizeof(TNo)); novo->valor=num; while (con<posicao-1) { aux2=aux2->prox; con++; } aux=aux2->prox; novo->ant=aux2; aux2->prox=novo; aux->ant=novo; novo->prox=aux; return 1; } void insereFim(TLista *L, TLista *U, int numero) { TLista novo=(TLista) malloc(sizeof(TNo)); novo->prox=NULL; novo->valor=numero; (*U)?novo->ant=*U,(*U)->prox=novo,*U=novo:*L = novo; *U = novo; } void botarCrescente(TLista *L) { TLista genesis = *L, ordenada; int gV,oV; while(genesis) { ordenada=genesis->prox; while(ordenada) { if(genesis->valor > ordenada->valor) { gV=genesis->valor; oV=ordenada->valor; ordenada->valor=gV; genesis->valor=oV; } ordenada = ordenada->prox; } genesis=genesis->prox; } } int tamanho (TLista L1) { TLista L=L1; if (!L) return 0; return (1+tamanho (L->prox)); } void inverterLista (TLista *L,TLista *U) { TLista aux=*L; TLista auxU=*U; *L=NULL; *U=NULL; while(aux) { inserir (&*L, &*U, aux->valor); aux=aux->prox; } } int pesquisaMaior(TLista L2) { TLista L=L2; if (!L) return 0; int maior = pesquisaMaior(L->prox); if (L->valor > maior) return L->valor; return maior; } int pesquisaMenor(TLista L2) { TLista L=L2; if (!L) return 0; int menor=L->valor; while(L) { if(L->valor < menor) { menor = L->valor; } L = L->prox; } return menor; } float media(TLista L2) { if (L2) { return (somaDosElementos(L2)/tamanho(L2)); } else return 0; } float somaDosElementos(TLista L2) { TLista L=L2; if (!L) { return 0; } else { return L->valor + somaDosElementos(L->prox); } } void remRepListaOrd(TLista L2) { TLista aux; TLista L=L2; if((!L)||(!L->prox)) return; if (L->valor == L->prox->valor) { L->prox->prox->ant=aux; aux = L->prox->prox; free (L->prox); aux->ant=L; L->prox = aux; remRepListaOrd(L); } else { if(!L->prox) return; remRepListaOrd(L->prox); } }
  4. Como posso melhorar meu código? Tudo funciona, mas tem como deixá-lo mais enxuto ou "profissional"? Obrigado! #include <stdio.h> #include <stdlib.h> #define TRUE 1 #define FALSE 0 typedef struct No { int valor; struct No *prox; } TNo; typedef TNo* TLista; int inserir (TLista *L, int numero); int remover (TLista *L, int numero); int alterar (TLista L, int velho, int novo); TLista buscar (TLista L, int numero); void exibir (TLista L); void mantem (TLista L,TLista *L3); float somaDosElementos(TLista L); int comparaListas (TLista L1, TLista L2);/*FAZER*/ void exibirInvertido (TLista L2); void botarCrescente(TLista *L); int inserirNoFim (TLista *L, int numero); void clonar (TLista *L, TLista L2); void inverterLista (TLista *L); int inserirNaPosicao (TLista *L, int numero, int posicao); int tamanhoDaLista (TLista L); int pesquisaMaior(TLista L2); int pesquisaMenor(TLista L2); int menu (TLista L, TLista L2, TLista L3); float media(TLista L); void remRepListaOrd(TLista L); int main (void) { TLista L = NULL, L2 = NULL, L3 = NULL; int opcao, num1, num2, alt, pos; do { opcao = menu (L,L2,L3); switch (opcao) { //inserção case 1: printf ("Entre com o número a ser inserido: "); scanf ("%d", &num1); printf (inserir (&L, num1)?"Elemento inserido!\n":"ERRO: Elemento não inserido!\n"); break; //remoção case 2: printf ("Entre com o número a ser removido: "); scanf ("%d", &num1); printf (remover (&L, num1)?"Elemento removido!\n":"ERRO: Elemento não removido!\n"); break; //alterar case 3: printf ("Entre com o número a ser alterado: "); scanf ("%d", &num1); printf ("Entre com o novo elemento: "); scanf ("%d", &num2); alt = alterar (L, num1, num2); if (alt != 0) { printf ("%d ocorrencias de %d alteradas!\n", alt, num1); } else { printf ("ERRO: Elemento não alterado!\n"); } break; //pesquisar case 4: printf ("Entre com o número a ser buscado: "); scanf ("%d", &num1); printf (buscar (L, num1)?"Elemento encontrado!\n":"Elemento não encontrado!\n"); break; //exibir case 5: if (!L) { printf("Lista vazia!\n"); } else { printf("Lista: "); exibir (L); printf("\n"); } break; //exibir invertido case 6: if (!L) { printf("Lista vazia!\n"); } else { printf("Lista: "); exibirInvertido (L); printf("\n"); } break; //CLONAR case 7: clonar (&L2,L); break; //INVERTER case 8: inverterLista (&L); break; //insere no fim case 9: printf ("Entre com o número a ser inserido: "); scanf ("%d", &num1); printf (inserirNoFim (&L, num1)?"Elemento inserido!\n":"ERRO: Elemento não inserido!\n"); break; //ordenar case 10:L3=NULL;mantem (L,&L3); botarCrescente (&L); break; //INSERIR NA POSIÇÃO case 11:printf ("Entre com o número a ser inserido: "); scanf ("%d", &num1); printf ("Entre com a posicao: "); scanf ("%d", &pos); printf (inserirNaPosicao (&L, num1, pos)?"Elemento inserido!\n":"ERRO: Elemento não inserido!\n"); break; //comparar case 12:printf (comparaListas (L, L2)?"Elemento encontrado!\n":"Elemento não encontrado!\n"); break; case 13:remRepListaOrd(L); break; //saída case 0: printf ("Fim do programa!\n"); break; //opção inválida default: printf ("Opção inválida! Tente novamente.\n"); } system ("pause"); } while (opcao != 0); return 0; } int inserir (TLista *L, int numero) { TLista aux = (TLista) malloc (sizeof(TNo)); if (!aux) { return FALSE; } else { aux->valor = numero; aux->prox = *L; *L = aux; return TRUE; } } int remover (TLista *L, int numero) { TLista aux1, aux2; int cont = 0; while ((*L) && ((*L)->valor == numero)) { aux1 = (*L)->prox; free (*L); cont++; *L = aux1; } if (*L) { aux2 = *L; aux1 = (*L)->prox; while (aux1) { if (aux1->valor == numero) { aux2->prox = aux1->prox; free (aux1); cont++; aux1 = aux2->prox; } else { aux2 = aux1; aux1 = aux1->prox; } } } return cont; } int alterar (TLista L, int velho, int novo) { TLista i=L; int cont=0; while (i != NULL) { if (i->valor == velho) { i->valor = novo; cont++; } i = i->prox; } return cont; } TLista buscar (TLista L, int numero) /*if (!L){return NULL;}if (L->valor == numero){return L;}return buscar (L->prox,numero);*/ { (!L)?NULL:(L->valor == numero)?L:buscar (L->prox,numero); } void exibir (TLista L2) { TLista L=L2; if(L) { printf ("%d ", L->valor); exibir (L->prox); } } int menu (TLista L, TLista L2, TLista L3) { int opcao; system ("cls"); printf ("\nTamanho da Lista: %i\n\n",tamanhoDaLista (L)); printf ("Lista Antes de Ordenar...: ");exibir (L3); printf ("|\n\n"); printf ("Lista Atual..................: ");exibir (L); printf ("|\n"); printf ("Menor elemento da lista......: %i. \n", pesquisaMenor(L)); printf ("Maior elemento da lista......: %i. \n", pesquisaMaior(L)); float x; (!L)?x=0:x=media(L); printf ("Media dos elementos da lista.: %.2f. \n\n", x); printf ("Clone da Lista Atual.....: ");exibir (L2); printf ("|\n\n"); printf ("Menu de opções:\n\n"); printf ("(1)\tInserir\n(2)\tRemover\n(3)\tAlterar\n"); printf ("(4)\tPesquisar\n(5)\tExibir na Ordem Natural\n"); printf ("(6)\tExibir na Ordem Inversa\n(7)\tClonar\n"); printf ("(8)\tInverter Lista\n"); printf ("(9)\tInsere no Fim\n(10)\tOrdenar Lista\n"); printf ("(11)\tInserir na Posicao\n"); printf ("(12)\tComparar Listas(FAZER)\n"); printf ("(13)\tRemove Repeticao de Lista Ja Ordenada\n"); printf ("(0)\tSair\n\n"); printf ("Entre Com a Opcao: "); scanf ("%d", &opcao); return opcao; } void botarCrescente(TLista *L) { TLista genesis = *L, ordenada; int gV,oV; while(genesis) { ordenada=genesis->prox; while(ordenada) { if(genesis->valor > ordenada->valor) { gV=genesis->valor; oV=ordenada->valor; ordenada->valor=gV; genesis->valor=oV; } ordenada = ordenada->prox; } genesis=genesis->prox; } } int inserirNoFim (TLista *L, int numero) { TLista aux=(TLista)malloc(sizeof(TNo)); TLista novo=(TLista)malloc(sizeof(TNo)); TLista aux2=(TLista)malloc(sizeof(TNo)); novo->valor=numero; aux2=*L; if((!*L)) { aux->valor=numero; aux->prox=*L; *L=aux; return TRUE; } else { while(aux2->prox) { aux2=aux2->prox; } aux=aux2->prox; aux2->prox=novo; novo->prox=aux; return TRUE; } } void clonar (TLista *L, TLista L2) { TLista aux=(TLista)malloc(sizeof(TNo)); *L=NULL; aux=L2; while(aux) { inserirNoFim (&*L, aux->valor); aux=aux->prox; } } void inverterLista (TLista *L) { TLista aux=(TLista)malloc(sizeof(TNo)); aux=*L; *L=NULL; while(aux) { inserir (&*L, aux->valor); aux=aux->prox; } } int inserirNaPosicao (TLista *L, int num, int posicao) { int con=0; TLista auxL=*L, aux; TLista novo=(TLista) malloc (sizeof(TNo)); novo->valor=num; if(!posicao||posicao>tamanhoDaLista(*L)+1) { return FALSE; } if(posicao==1) { inserir (&*L, num); return TRUE; } if(posicao==tamanhoDaLista(*L)+1) { inserirNoFim(&*L, num); return 1; } posicao=posicao-1; while (con<posicao-1) { auxL=auxL->prox; con++; } aux=auxL->prox; auxL->prox=novo; novo->prox=aux; return TRUE; } int tamanhoDaLista (TLista L2) /*int tam=0;TLista aux=L;while(aux){aux=aux->prox;tam++;}return tam;}*/ { TLista L=L2; if (!L) { return 0; } else { return (1 + tamanhoDaLista(L->prox)); } } int pesquisaMaior(TLista L2) /*if (!L2) return 0;TLista L=L2;int maior = L->valor;while(L){if(L->valor > maior){maior = L->valor;}L=L->prox;}return maior;*/ { TLista L=L2; if (!L) return 0; int maior = pesquisaMaior(L->prox); if (L->valor > maior) return L->valor; return maior; } int pesquisaMenor(TLista L2) { TLista L=L2; if (!L) return 0; int menor=L->valor; while(L) { if(L->valor < menor) { menor = L->valor; } L = L->prox; } return menor; } float media(TLista L2) { return (somaDosElementos(L2)/tamanhoDaLista(L2)); } void exibirInvertido (TLista L2) { TLista L=L2; if(L) { exibirInvertido (L->prox); printf ("%d ", L->valor); } } int comparaListas (TLista L1, TLista L2)/*GOSTARIA DE FAZER RECURSIVAMENTE*/ { TLista l1=L1; while (l1) { if (!buscar(L2,l1->valor)) { return 0; } l1=l1->prox; } return 1; } float somaDosElementos(TLista L2) { TLista L=L2; if (!L) { return 0; } else { return L->valor + somaDosElementos(L->prox); } } void remRepListaOrd(TLista L) { TLista aux; if((!L)||(!L->prox)) return; (L->valor == L->prox->valor)?aux = L->prox->prox,free (L->prox),L->prox = aux,remRepListaOrd(L):remRepListaOrd(L->prox); } void mantem (TLista L1,TLista *L3) { TLista L=L1; if (!L) { return; } else { inserirNoFim (&*L3, L->valor); } mantem (L->prox,&*L3); }
  5. @arfneto Tá errado não, tá certo. "não há como saber qual das operações vai ser executada primeiro" ??????????????????????????? Leu a parte que escrevi que é desnecessário? Enfim... Sério???? Se você não me avisa! Caramba... Sério??? Nossa! Acho que você deveria estudar mais aritmética de ponteiros.... talvez entenda o que foi feito. Compilador online? Puts... É só admitir que não sabe... Você e 3 pessoas vão rir muito. O resto vai saber o que houve...
  6. O segundo return que botei na comparaString é desnecessário...
  7. @arfneto "Você sabe o que é ambiguidade? Um tópico que fala em inserir na ordem o número 4 na quarta posição e a série é 1 2 3 5 6 7 8 não é ambíguo pra você?" Não... qualquer pessoa teria lido a expressão "por exemplo" e saberia que se tratava apenas de um exemplo! Ajudar é bem diferente disso aí. Retiro o convite. Obrigado!
  8. "Sua pergunta é ambígua: você diz que quer inserir na quarta posição, mas sugere que quer também inserir na ordem numérica. Se quer inserir na quarta posição é uma coisa, se quer inserir na ordem é outra." 1. Aí, tu forçou a barra...momento algum escrevi "BOTAR EM ORDEM" 2. No início eu escrevi "Por exemplo, "...chegou a ver? 3. aiai...
  9. Eita! Custa você admitir que não sabe? Segue: String1...: azul String2...: aazz uull Existem 8 caracteres comuns entre as duas strings -------------------------------- Process exited after 17.12 seconds with return value 0 Pressione qualquer tecla para continuar. . . 4 0 0 String1...: uma string String2...: uma strinG Existem 9 caracteres comuns entre as duas strings -------------------------------- Process exited after 14.53 seconds with return value 0 Pressione qualquer tecla para continuar. . . Se você conseguir admitir que estou certo, pode me ajudar a não contar as repetições? aaaa x aa retornar "1". Pensei em pesquisar e retornar 1 ou 0 se achar. Daí um "IF". Se quiser continuar teimando, tudo bem.
  10. @arfneto String1...: abcdefghija String2...: a Existem 2 caracteres comuns entre as duas strings -------------------------------- Process exited after 9.396 seconds with return value 0 Pressione qualquer tecla para continuar. . . String1...: a a a String2...: a Existem 3 caracteres comuns entre as duas strings -------------------------------- Process exited after 3.472 seconds with return value 0 Pressione qualquer tecla para continuar. . . String1...: bbb String2...: ab Existem 3 caracteres comuns entre as duas strings -------------------------------- Process exited after 6.962 seconds with return value 0 Pressione qualquer tecla para continuar. . . String1...: bbb String2...: bab Existem 6 caracteres comuns entre as duas strings -------------------------------- Process exited after 2.625 seconds with return value 0 Pressione qualquer tecla para continuar. . . String1...: MATRIX String2...: MATRISX Existem 6 caracteres comuns entre as duas strings -------------------------------- Process exited after 9.389 seconds with return value 0 Pressione qualquer tecla para continuar. . .
  11. @arfneto Se não funciona no seu compilador... paciência. você querendo ou não está certa. Abraços.
  12. Dado o código, como incluir número em determinada posição na LDE criada? Por exemplo, lista criada: 1 2 3 5 6 7 8. Quero incluir o 4 na quarta posição, tornando a lista assim: 1 2 3 4 5 6 7 8. Segue o código: #include <stdio.h> #include <stdlib.h> #include <locale.h> typedef struct No { int valor; struct No *prox, *ant; } TNo; typedef TNo* TLista; int inserir (TLista *Lista, TLista *U, int num) { TLista aux = (TLista) malloc (sizeof(TNo)); aux->valor = num; aux->prox = *Lista; aux->ant = NULL; (*Lista)?(*Lista)->ant = aux:*U = aux; *Lista = aux; } void exibir (TLista Lista) { if(Lista) { printf ("%d ", Lista->valor); exibir (Lista->prox); } }
  13. Tem razão pequeno gafanhoto! Viu? nem sempre discordo de você. Segue a função que inclui os itens na lista e da onde surge o "U". typedef struct No { int valor; struct No *prox, *ant; } TNo; typedef TNo* TLista; void inserir (TLista *L, TLista *U, int num) { TLista aux = (TLista) malloc (sizeof(TNo)); { aux->valor = num; aux->prox = *L; aux->ant = NULL; (*L)?(*L)->ant = aux:*U = aux; *L = aux; } } void exibir (TLista L) { if(L) { printf ("%d ", L->valor); exibir (L->prox); } } void exibirAoContrario (TLista U) { if(U) { printf ("%d ", U->valor); exibirAoContrario (U->ant); } }
  14. Se ninguém resolveu antes de mim, por que não posso marcar a minha solução como solução. Se você tivesse resolvido eu marcaria a sua. Simples. Pela enésima vez, a sua tem for. Não serve. Obrigado mesmo assim e até a próxima.
  15. Imagino que tenha um programa todo onde testou isso (lógico). Poste o programa(não precisa). E teste (aff) Evite chamar variáveis de "aux"...(vou continuar chamando; irrelevante). Se a lista está vazia simplesmente retorne. Não há sentido em deslocar todo o código da função para a direita por um caso particular que deve acontecer em uma fração modesta das execuções. Só dificultaa leitura e manutenção do código. (você não entendeu a função) E entenda que se aux está posicionada para o inicio da lista adivinha o que vai ter em aux->ant? NADA. Zero, NULL. Não vai listar nadinha exceto o primeiro valor...(extamante, assim o laço termina; não entendeu o código outra vez). O tópico aqui era gerar uma lista inversa e e não simplesmente listar ao contrário (isso sim é relevante; no programa, a lista "U" é a inversa da lista original "L".
  16. void exibirAoContrario (TLista U) { TLista aux; //verificando se a lista está vazia if (!U) { printf ("Lista vazia!\n"); } else { printf ("Lista: "); aux = U; while (aux) { printf ("%d ", aux->valor); aux = aux->ant; } printf ("\n"); } }
  17. #include <string.h> #include <strings.h> #include <stdio.h> #include <conio.h> #include <stdlib.h> int comparaString2(char str1,char* str2); int comparaString (char* str1,char* str2); int main(void) { int cont=0; char str1[100],str2[100]; fflush(stdin); printf("\nString1...:\n"); gets(str1); fflush(stdin); printf("\nString2...:\n"); gets(str2); cont=comparaString (str1,str2); printf("\nExistem %i caracteres comuns entre as duas strings\n",cont); return 0; } int comparaString (char* str1,char* str2) { if (!str1[0]) { return 0; } return(comparaString2(str1[0],str2)+comparaString(++str1,str2)); return (comparaString (++str1,str2)); } int comparaString2(char str1,char* str2) { if (!str2[0]) { return 0; } if (str2[0]==str1) { return (1+comparaString2(str1,++str2)); } else return comparaString2(str1,++str2); } Solução!
  18. @arfneto Não vale porque tem laço "for". Vou tentar por aqui, se eu conseguir eu posto. Abraços. Você que não entendeu muito bem, mas deixa pra lá. Vou tentar sozinho ou esperar alguém que me ajude. Quando eu conseguir eu mostro aqui. Até a próxima!
  19. @arfneto Não vale porque tem laço "for". Vou tentar por aqui, se eu conseguir eu posto. Abraços.
  20. @arfneto existe sim, são só jogo de palavras usados para compreensão do que se quer.
  21. @arfneto funciona filho, eu faço isso. rs Ternário: cont >= 0 ? aux++ : aux=0; ao invés de if (cont > = 0) aux++; else aux=0; @arfneto "Copie da que eu postei. É quase igual. Só muda o loop interno." Não funciona. a sua é para string; não consegui adaptar para caracteres. Isso que estou tentando.
  22. @arfneto Acho que você não entendeu, mas deixa prá lá. É só salvar como .cpp que funciona. Não estou preocupado com essas coisas agora. Sei todas as "regras de etiqueta" dos códigos. Perda de tempo... estou queimando os neurônios aqui ainda com a função recursiva! KKKK Por exemplo, eu uso operador ternário nos meus códigos, você não. Estou escrevendo para tentar entender a recursividade. E por fim, obrigado por se disponibilizar a ajudar.
  23. @arfneto Eu sei. No DEVC++, se você gravar o arquivo como .c, ele não aceita declarar dentro do for. "50 2 D:\desafio.c [Error] 'for' loop initial declarations are only allowed in C99 or C11 mode" @arfneto int comparaString (char* str1,char* str2) { int i,j,cont=0,CONT=0; for(i=0;str1[i]!=NULL;i++) { for(j=0;str2[j]!=NULL;j++) { if(str1[i]==str2[j]) { cont++;break; } } } for(i=0;str2[i]!=NULL;i++) { for(j=0;str1[j]!=NULL;j++) { if(str2[i]==str1[j]) { CONT++;break; } } } if (CONT>cont) { return cont; } else { return CONT; } } Não conta caracter repetido
  24. @arfneto não importa. cada "a" é considerado um "a" diferente. Esse foi o desafio: Develop a recursive function that determines the number of common characters between two strings s1 and s2. Grades: i. The solution must be in the C programming language; ii. If the same character appears n times in a given string, it will not be considered an error if your solution counts this character n times; iii. If your solution is broken down into more than one function (so that the main one - which solves the proposed problem - calls other helpers), all functions must be recursive; @arfneto "não use char[100]. É limitante a toa. Se possível use "const char*"." Sim, depois eu deixo o código elegante. @arfneto "um "problema": não declare variáveis de controle fora do loop, em especial ums com nomes comuns tipo i e j como aqui. Isso sempre cai na sua cabeça. A comunidade lutou por anos até o comitê ISO que controla C mudar a linguagem para aceitar essas declarações no próprio for. Só que foi no final dos anos 80. É norma em toda empresa que tenha um código de aderência para programação, em toda escola séria: nada de globais, total foco na redução de escopo de variáveis. Nada de variáveis de controle soltas pelo programa. Tanto é assim que desde '17 por exemplo em C++ se pode declarar variáveis dentro de if() e switch() também, e variáveis podem ser declaradas dentro de qualquer bloco {}." arquivos ".c" não aceitam declarar a variável dentro do for Só a minha iterativa que funcionou

Sobre o Clube do Hardware

No ar desde 1996, o Clube do Hardware é uma das maiores, mais antigas e mais respeitadas comunidades sobre tecnologia do Brasil. Leia mais

Direitos autorais

Não permitimos a cópia ou reprodução do conteúdo do nosso site, fórum, newsletters e redes sociais, mesmo citando-se a fonte. Leia mais

×
×
  • Criar novo...

 

GRÁTIS: ebook Redes Wi-Fi – 2ª Edição

EBOOK GRÁTIS!

CLIQUE AQUI E BAIXE AGORA MESMO!