Get letter by letter to a doubly linked list

人走茶凉 提交于 2019-12-25 06:21:10

问题


I'm trying to write a program that takes a word letter by letter in every node of a doubly linked list and then with a function I wrote it will check if the word is a palindrome.

When I compile my code I'm having problems in the part of the code it takes the input, so I would like to know how I can do it.

int main(){
  char c;
  Llista * list;
  Dada head = {0, NULL, NULL};
  printf("insertar palabra para comprobar si es palindromo");
  while((c=getchar()) != '\n'){
    InsertAtTail(c);
  }

  palindromo(list);

  return 0;
}

This is all the code i have written:

#include <stdio.h>
#include <stdlib.h>

typedef struct dada{

char c;
struct dada *seguent;
struct dada *anterior;

}Dada;


typedef struct lista{

Dada *principi;
Dada *fin;
unsigned nelements;

}Llista;

int palindromo(Llista * lista);
struct dada* GetNewNode(char x);
void InsertAtTail(char x);
struct dada* head;

int main(){
  char c;
  Llista * list;
  Dada head = {0, NULL, NULL};
  printf("insertar palabra para comprobar si es palindromo");
  while((c=getchar()) != '\n'){
    InsertAtTail(c);
  }

  palindromo(list);

  return 0;
}

void InsertAtTail(char x) {
    struct dada* temp = head;
    struct dada* newNode = GetNewNode(x);
    if(head == NULL) {
        head = newNode;
        return;
    }
    while(temp->seguent != NULL) temp = temp->seguent;
    temp->seguent = newNode;
    newNode->anterior = temp;
}


struct dada* GetNewNode(char x) {
    struct dada* newNode
        = (struct dada*)malloc(sizeof(struct dada));
    newNode->c = x;
    newNode->seguent = NULL;
    newNode->anterior = NULL;
    return newNode;
}

int palindromo(Llista * lista){
   int palindromo = 0;
   int descartado = 0;
   Dada *aux = lista->principi;
   Dada *aux2 = lista->fin;

   while(aux->seguent != aux2->anterior && descartado==0){
    if(aux->c != aux2->c){
        descartado = 1;
    }
    else{
       aux = aux->seguent;
       aux2 = aux2->anterior;
    }
   }
   if(descartado==1){
    palindromo=0;
   }
   else{
    palindromo=1;
   }
   return palindromo;
}

回答1:


Llista dadaToList(Dada *node){
    Llista ret = { NULL, NULL, 0};
    if(!node) return ret;

    ret.principi = node;
    ret.nelements = 0;
    while(node->seguent != NULL){
        node = node->seguent;
        ++ret.nelements;
    }
    ret.fin = node;
    return ret;
}

int main(void){
    char c;
    Llista list;
    printf("insertar palabra para comprobar si es palindromo");
    while((c=getchar()) != '\n'){
        InsertAtTail(c);
    }
    list = dadaToList(head);//you need set to `list` from `head`
    if(palindromo(&list))
        printf("palindromo\n");

    //deallocation
    return 0;
}


来源:https://stackoverflow.com/questions/30852441/get-letter-by-letter-to-a-doubly-linked-list

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!