Lists in C

  • (2 Pages)
  • +
  • 1
  • 2

15 Replies - 1488 Views - Last Post: 12 November 2008 - 04:35 PM Rate Topic: -----

#1 ultimo1234   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 7
  • Joined: 10-November 08

Lists in C

Post icon  Posted 10 November 2008 - 07:30 PM

Hi there, this is an assignment from school in which i need some help. After struggling a little, i could make my list program in c, using only 1 char, not really that hard, but for some reason i cant do the next assignment

I gotta do it now with a full word, and sorting them. The program i made sort them sometimes, sometimes it doesnt, and throws random ASCII

Any directions would help a lot

note: program is in spanish, first option is instert element, second is delete element.

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

struct tiponodo //estructura autoreferencial
{
	char *letra;
	struct tiponodo *next;
};

typedef tiponodo *tiponodoptr; //tipo de dato nodo apuntador

int IsEmpty(tiponodoptr sptr)
{
	if (sptr == NULL)
		return 1;
	else
		return 0;
}

void Insert(tiponodoptr *sptr, char *letra)
//inserta una letra en la lista en orden alfabetico

{
	tiponodoptr nuevo, previo, actual;
	nuevo = (tiponodo *) malloc(sizeof(tiponodo)); //crear un apuntador
	if (nuevo != NULL)	//si fue creado
	{
		nuevo -> letra = letra;
		nuevo -> next = NULL;
		previo = NULL;
		actual = *sptr;
		while (actual != NULL && letra > actual -> letra) //buscar la posicion de actual
		{
			previo = actual; //avanzar al siguiente nodo
			actual = actual -> next; //una posición mas adelante
		}

		if (previo == NULL)	//llegue al final de la lista
		{
			nuevo -> next = *sptr;
			*sptr = nuevo;
		}
		else
		{
			previo -> next = nuevo;
			nuevo -> next = actual;
		}
	}
	else
		printf("%s no fue insertado!!!, Memoria no disponible!!!\n", letra);
}

char *Delete(tiponodoptr *sptr, char *letra)
//borra un elemento de la lista y regresa el elemento borrado
{
	tiponodoptr previo, actual, temporal;
	if (letra == (*sptr)->letra)	//primer elemento de la lista
	{
		temporal = *sptr;
		*sptr = (*sptr) -> next;	//apuntar al siguiente nodo
		free(temporal);				//liberar la memoria del nodo
		return letra;				//regresa la letra borrada
	}
	else		//buscar el elemento a borrar
	{	
		previo = *sptr;
		actual = (*sptr) -> next;
		while (actual != NULL && actual -> letra != letra)
		{
			previo=actual;			//avanza al siguiente nodo
			actual=previo -> next;	//una posicion mas adelantada
		}
		if (actual != NULL)		//se encontro la letra  a borrar
		{
			temporal = actual;
			previo -> next = actual-> next;
			free(temporal);
			return letra;
		}
	}
	return " ";
}

void PrintList(tiponodoptr actualptr)
{
	if (actualptr == NULL)
		printf("La lista es: \n");
	else
	{
		printf("La lista es: \n");
	while (actualptr != NULL)
	{
		printf("%s -->" , &actualptr->letra);
		actualptr = actualptr->next;
	}
	printf("NULL\n\n");
}
}


void operacion()
{
	printf("Selecciona una opcion: \n");
	printf("1.- Insertar un elemento en la lista\n");
	printf("2.- Borrar un elemento en la lista \n");
	printf("3.- Terminar\n");
}

int main()
{
	tiponodoptr startlista = NULL;
	int op;
	char *item;

	operacion();
	printf("Elije una opcion ");
	scanf("%d",&op);
	fflush(stdin);
	while (op != 3)
	{
		switch (op)
		{
		case 1:
			printf("Dame una letra: ");
			fflush(stdin);
			//gets(item);
			scanf("%s", &item);
			Insert(&startlista, item);
			PrintList(startlista);
			break;
		case 2:
			if (!IsEmpty(startlista))
			{
				printf("Dame la palabra a borrar: ");
				fflush(stdin);
				//gets(item);
				scanf("%s",&item);
				if (Delete(&startlista, item))
				{
					printf("[%s] borrado!!! \n", &item);
					PrintList(startlista);
				}
				else
					printf("[%s] No esta en la lista \n\n" , &item);
			}
			else
				printf("la lista esta vacia!!!\n\n");
			operacion();
			break;
		}
		printf("Elije la opcion ");
		scanf("%d", &op);
	}
	printf("Fin del programa!!!\n\n");
}



Is This A Good Question/Topic? 0
  • +

Replies To: Lists in C

#2 GWatt   User is offline

  • member icon

Reputation: 312
  • View blog
  • Posts: 3,107
  • Joined: 01-December 05

Re: Lists in C

Posted 10 November 2008 - 08:00 PM

I'm guessing it's because you don't terminate your strings. When you use char* they must have a '\0' character at the end. I skimmed through your code and noticed that you never used a '\0' at any point, which is why I think that's your problem.
Was This Post Helpful? 0
  • +
  • -

#3 ultimo1234   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 7
  • Joined: 10-November 08

Re: Lists in C

Posted 10 November 2008 - 10:00 PM

and uhm... how do i add that??
Was This Post Helpful? 0
  • +
  • -

#4 KYA   User is offline

  • Wubba lubba dub dub!
  • member icon

Reputation: 3213
  • View blog
  • Posts: 19,241
  • Joined: 14-September 07

Re: Lists in C

Posted 10 November 2008 - 10:04 PM

Append to the end of the "string".

I have an interesting time understanding your code since I don't speak/read that language :(
Was This Post Helpful? 0
  • +
  • -

#5 GWatt   User is offline

  • member icon

Reputation: 312
  • View blog
  • Posts: 3,107
  • Joined: 01-December 05

Re: Lists in C

Posted 10 November 2008 - 10:16 PM

Looking at it again, I don't think that's your problem. Sorry for the bad advice. It actually looks like when you delete an element from the list that you don't adjust the pointer to the next node.

if (letra == (*sptr)->letra)    //primer elemento de la lista
    {
        temporal = *sptr;
        *sptr = (*sptr) -> next;    //apuntar al siguiente nodo
        free(temporal);                //liberar la memoria del nodo
        return letra;                //regresa la letra borrada
    }

Actually, you can't compare char* with == you have to use the strcmp function.
#include <string.h>
if (strcmp(strOne, strTwo) == 0) 
/* strcmp returns 0 if they are the same
 * a positive int if the first string is greater than the second
*/ and a negative int if visa versa.

Was This Post Helpful? 0
  • +
  • -

#6 KYA   User is offline

  • Wubba lubba dub dub!
  • member icon

Reputation: 3213
  • View blog
  • Posts: 19,241
  • Joined: 14-September 07

Re: Lists in C

Posted 10 November 2008 - 10:17 PM

edit: wrong thread ><

This post has been edited by KYA: 10 November 2008 - 10:17 PM

Was This Post Helpful? 0
  • +
  • -

#7 ultimo1234   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 7
  • Joined: 10-November 08

Re: Lists in C

Posted 10 November 2008 - 10:21 PM

so I try adding this : strcat(item, "\0");
but the program crashes when entering a word....
any insight?
Was This Post Helpful? 0
  • +
  • -

#8 KYA   User is offline

  • Wubba lubba dub dub!
  • member icon

Reputation: 3213
  • View blog
  • Posts: 19,241
  • Joined: 14-September 07

Re: Lists in C

Posted 10 November 2008 - 10:33 PM

crashing would indicate an array out of bounds error or a pointer issue, if there was a specific crash message that would help
Was This Post Helpful? 0
  • +
  • -

#9 ultimo1234   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 7
  • Joined: 10-November 08

Re: Lists in C

Posted 10 November 2008 - 10:38 PM

ok so I changed to strcmp, but crashes after i insert the second word.

how to make a comparison like i did with ">"?

heres the code redone:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

struct tiponodo //estructura autoreferencial
{
	char *letra;
	struct tiponodo *next;
};

typedef tiponodo *tiponodoptr; //tipo de dato nodo apuntador

int IsEmpty(tiponodoptr sptr)
{
	if (sptr == NULL)
		return 1;
	else
		return 0;
}

void Insert(tiponodoptr *sptr, char *letra)
//inserta una letra en la lista en orden alfabetico

{
	tiponodoptr nuevo, previo, actual;
	nuevo = (tiponodo *) malloc(sizeof(tiponodo)); //crear un apuntador
	if (nuevo != NULL)	//si fue creado
	{
		nuevo -> letra = letra;
		nuevo -> next = NULL;
		previo = NULL;
		actual = *sptr;
		while ((actual != NULL) && (strcmp(letra,actual -> letra)==1)) //buscar la posicion de actual
		{
			previo = actual; //avanzar al siguiente nodo
			actual = actual -> next; //una posición mas adelante
		}

		if (previo == NULL)	//llegue al final de la lista
		{
			nuevo -> next = *sptr;
			*sptr = nuevo;
		}
		else
		{
			previo -> next = nuevo;
			nuevo -> next = actual;
		}
	}
	else
		printf("%s no fue insertado!!!, Memoria no disponible!!!\n", letra);
}

char *Delete(tiponodoptr *sptr, char *letra)
//borra un elemento de la lista y regresa el elemento borrado
{
	tiponodoptr previo, actual, temporal;
	if (letra == (*sptr)->letra)	//primer elemento de la lista
	{
		temporal = *sptr;
		*sptr = (*sptr) -> next;	//apuntar al siguiente nodo
		free(temporal);				//liberar la memoria del nodo
		return letra;				//regresa la letra borrada
	}
	else		//buscar el elemento a borrar
	{	
		previo = *sptr;
		actual = (*sptr) -> next;
		while (actual != NULL && strcmp(actual -> letra, letra)==1)
		{
			previo=actual;			//avanza al siguiente nodo
			actual=previo -> next;	//una posicion mas adelantada
		}
		if (actual != NULL)		//se encontro la letra  a borrar
		{
			temporal = actual;
			previo -> next = actual-> next;
			free(temporal);
			return letra;
		}
	}
	return " ";
}

void PrintList(tiponodoptr actualptr)
{
	if (actualptr == NULL)
		printf("La lista es: \n");
	else
	{
		printf("La lista es: \n");
	while (actualptr != NULL)
	{
		printf("%s -->" , &actualptr->letra);
		actualptr = actualptr->next;
	}
	printf("NULL\n\n");
}
}


void operacion()
{
	printf("Selecciona una opcion: \n");
	printf("1.- Insertar un elemento en la lista\n");
	printf("2.- Borrar un elemento en la lista \n");
	printf("3.- Terminar\n");
}

void main()
{
	tiponodoptr startlista = NULL;
	int op;
	char *item;

	operacion();
	printf("Elije una opcion ");
	scanf("%d",&op);
	fflush(stdin);
	while (op != 3)
	{
		switch (op)
		{
		case 1:
			printf("Dame una letra: ");
			fflush(stdin);
			//gets(item);
			scanf("%s", &item);
			//strcat(item, "\0");
			Insert(&startlista, item);
			PrintList(startlista);
			break;
		case 2:
			if (!IsEmpty(startlista))
			{
				printf("Dame la palabra a borrar: ");
				fflush(stdin);
				//gets(item);
				scanf("%s",&item);
				//strcat(item, "\0");
				if (Delete(&startlista, item))
				{
					printf("[%s] borrado!!! \n", &item);
					PrintList(startlista);
				}
				else
					printf("[%s] No esta en la lista \n\n" , &item);
			}
			else
				printf("la lista esta vacia!!!\n\n");
			operacion();
			break;
		}
		printf("Elije la opcion ");
		scanf("%d", &op);
	}
	printf("Fin del programa!!!\n\n");
}


Was This Post Helpful? 0
  • +
  • -

#10 GWatt   User is offline

  • member icon

Reputation: 312
  • View blog
  • Posts: 3,107
  • Joined: 01-December 05

Re: Lists in C

Posted 10 November 2008 - 10:39 PM

Like KYA said, can you post your error message? That would help alot.
Was This Post Helpful? 0
  • +
  • -

#11 ultimo1234   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 7
  • Joined: 10-November 08

Re: Lists in C

Posted 10 November 2008 - 10:49 PM

well it kinda just crashes without telling me much, all i could get is this:
Exception Information
Code: 0xc0000005 Flags: 0x00000000
Record: 0x00000000000000 Address: 0x000000000040def0

plus system info, dunno if it helps
Was This Post Helpful? 0
  • +
  • -

#12 David W   User is offline

  • DIC supporter
  • member icon

Reputation: 298
  • View blog
  • Posts: 1,839
  • Joined: 20-September 08

Re: Lists in C

Posted 11 November 2008 - 03:00 AM

Some ?quick changes/cuts? ... just to get your code to compile and produce some ?reasonable? output ... :D

I don't know any Spanish :)
/* 
    Some ?quick changes/cuts? ... just to get your code to compile 
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define MAX 20

struct tiponodo //estructura autoreferencial
{
    char letra[MAX];
    struct tiponodo *next;
};

typedef struct tiponodo* tiponodoptr; //tipo de dato nodo apuntador

int IsEmpty(tiponodoptr sptr)
{
    if (sptr == NULL)
        return 1;
    else
        return 0;
}

void Insert(tiponodoptr* sptr, char* letra)
//inserta una letra en la lista en orden alfabetico

{
    tiponodoptr nuevo, previo, actual;
    nuevo = (struct tiponodo*) malloc(sizeof(struct tiponodo)); //crear un apuntador
    if (nuevo != NULL)    //si fue creado
    {
        strcpy( nuevo->letra, letra);
        nuevo->next = NULL;
        previo = NULL;
        actual = *sptr;
        while (actual != NULL && letra > actual -> letra) //buscar la posicion de actual
        {
            previo = actual; //avanzar al siguiente nodo
            actual = actual -> next; //una posición mas adelante
        }

        if (previo == NULL)    //llegue al final de la lista
        {
            nuevo -> next = *sptr;
            *sptr = nuevo;
        }
        else
        {
            previo->next = nuevo;
            nuevo->next = actual;
        }
    }
    else
        printf("%s no fue insertado!!!, Memoria no disponible!!!\n", letra);
}


void PrintList(tiponodoptr actualptr)
{
    if (actualptr == NULL)
        printf("La lista es: \n");
    else
    {
        printf("La lista es: \n");
        while (actualptr != NULL)
        {
            printf("%s -->" , actualptr->letra);
            actualptr = actualptr->next;
        }
    printf("NULL\n\n");
    }
}

void operacion()
{
    printf("Selecciona una opcion ... \n");
    printf("1 - Insertar un elemento en la lista\n");
    printf("2 - Borrar un elemento en la lista \n");
    printf("3 - Terminar\n");
}

int main()
{
    tiponodoptr startlista = NULL;
    int c, op;
    char item[MAX];
    
    do
    {
        operacion();
        printf("\nElije la opcion : ");
        scanf("%d", &op);
        c=op;
        while(c!='\n') c=getchar(); /* 'flush' stdin ... */
        
        switch (op)
        {
            case 1:
                printf("Dame una letra: ");
                scanf("  %s", item); /* to skip over leading spaces */
                while((c=getchar())!='\n') c=getchar();
                Insert(&startlista, item);
                PrintList(startlista);
            break;
            
            case 2:
                printf("UNDER CONSTRUCTION.\n");
            break;
            
            case 3:
                printf("Fin del programa!!!\n\n");                
            break;
            
            default:
                printf("NOT a valid choice.\n");
        }
        
    }while(op != 3);
    
    getchar();
    return 0;
}

Was This Post Helpful? 0
  • +
  • -

#13 ultimo1234   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 7
  • Joined: 10-November 08

Re: Lists in C

Posted 11 November 2008 - 03:14 AM

Yes! no errors and some good progress, although it doesnt sort the words alphabetically... well it kinda does sometimes... still dont get it :(
Was This Post Helpful? 0
  • +
  • -

#14 David W   User is offline

  • DIC supporter
  • member icon

Reputation: 298
  • View blog
  • Posts: 1,839
  • Joined: 20-September 08

Re: Lists in C

Posted 11 November 2008 - 05:55 AM

View Postultimo1234, on 11 Nov, 2008 - 02:14 AM, said:

Yes! no errors and some good progress, although it doesnt sort the words alphabetically... well it kinda does sometimes... still dont get it :(


One simple and ?sometimes faster? way to 'sort' a linked list

may be ?

to copy all the pointers in the list to an array of pointers ...

then adjust that index array of pointers to be in the order desired in your sort.

This post has been edited by David W: 11 November 2008 - 07:26 AM

Was This Post Helpful? 0
  • +
  • -

#15 ultimo1234   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 7
  • Joined: 10-November 08

Re: Lists in C

Posted 12 November 2008 - 03:32 PM

just in case someone needs it, here it is complete
Program captures names and sorts them, using pointers

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

#define MAX 20

struct tiponodo //estructura autoreferencial
{
	char letra[MAX];
	
	struct tiponodo *next;
};

typedef struct tiponodo* tiponodoptr; //tipo de dato nodo apuntador

int IsEmpty(tiponodoptr sptr)
{
	if (sptr == NULL)
		return 1;
	else
		return 0;
}

void Insert(tiponodoptr* sptr, char* letra)
//inserta una palabra en la lista en orden alfabetico

{
	tiponodoptr nuevo, previo, actual;
	nuevo = (struct tiponodo*) malloc(sizeof(struct tiponodo)); //crear un apuntador
	if (nuevo != NULL)	//si fue creado
	{
		strcpy( nuevo->letra, letra);
		nuevo->next = NULL;
		previo = NULL;
		actual = *sptr;
		while (actual != NULL && strcmp(letra, actual -> letra)<0)  //buscar la posicion de actual
		{
			previo = actual; //avanzar al siguiente nodo
			actual = actual -> next; //una posición mas adelante
		}

		if (previo == NULL)	//llegue al final de la lista
		{
			nuevo -> next = *sptr;
			*sptr = nuevo;
		}
		else
		{
			previo->next = nuevo;
			nuevo->next = actual;
		}
	}
	else
		printf("%s no fue insertado!!!, Memoria no disponible!!!\n", letra);
}

char *Delete(tiponodoptr *sptr, char *letra)
//borra un elemento de la lista y regresa el elemento borrado
{
	tiponodoptr previo, actual, temporal;
	if (strcmp(letra,((*sptr) -> letra))==0)	//primer elemento de la lista
	{
		temporal = *sptr;
		*sptr = (*sptr) -> next;	//apuntar al siguiente nodo
		free(temporal);				//liberar la memoria del nodo
		return letra;				//regresa la letra borrada
	}
	else		//buscar el elemento a borrar
	{	
		previo = *sptr;
		actual = (*sptr) -> next;
		while (actual != NULL && strcmp(actual -> letra,letra)==1)
		{
			previo=actual;			//avanza al siguiente nodo
			actual=previo -> next;	//una posicion mas adelantada
		}
		if (actual != NULL)		//se encontro la letra  a borrar
		{
			temporal = actual;
			previo -> next = actual-> next;
			free(temporal);
			return letra;
		}
	}
	return " ";
}


void PrintList(tiponodoptr actualptr)
{
	if (actualptr == NULL)
		printf("La lista es: \n");
	else
	{
		printf("La lista es: \n");
		while (actualptr != NULL)
		{
			printf("%s -->" , actualptr->letra);
			actualptr = actualptr->next;
		}
	printf("NULL\n\n");
	}
}

void operacion() //menu
{
	printf("Selecciona una opcion ... \n");
	printf("1 - Insertar un elemento en la lista\n");
	printf("2 - Borrar un elemento en la lista \n");
	printf("3 - Terminar\n");
}

int main() //menu
{
	tiponodoptr startlista = NULL;
	int c, op;
	char item[MAX];
	do
	{
		operacion();
		printf("\nElije la opcion : ");
		scanf("%d", &op);
		c=op;
		while(c!='\n') c=getchar(); /* 'flush' stdin ... */
		
		switch (op)
		{
			case 1:
				printf("Dame una letra: ");
				scanf("  %s", item); 
				while((c=getchar())!='\n') c=getchar();
				Insert(&startlista, item);
				PrintList(startlista);
				fflush(stdin);
			break;
			
			case 2:
				if (!IsEmpty(startlista))
			{
				printf("Dame la palabra a borrar: ");
				fflush(stdin);
				scanf("%s",&item);
				if (Delete(&startlista, item))
				{
					printf("[%s] borrado!!! \n", &item);
					PrintList(startlista);
				}
				else
					printf("[%s] No esta en la lista \n\n" , &item);
			}
			else
				printf("la lista esta vacia!!!\n\n");
   				fflush(stdin);
			break;
			
			case 3:
				printf("Fin del programa!!!\n\n");				
			break;
			
			default:
				printf("NOT a valid choice.\n");
		}
		
	}while(op != 3);
	
	getchar();
	return 0;
}



Was This Post Helpful? 0
  • +
  • -

  • (2 Pages)
  • +
  • 1
  • 2