Thread: Linked List program need help

  1. #1
    Registered User
    Join Date
    Aug 2004
    Posts
    2

    Linked List program need help

    hi, i have this Linked list program below which appears errors during execution ... anyone fix it for me PLEASE ???

    Code:
    
    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    
    
    typedef struct _order_      
    {
    	char Name[31];
    	char Album[31];
    	int  Req;              
    	int  Year;
    	int  Qty;    
    	char trackTitle[50];
        char trackTime[50];
    	struct _order_  *Next;  
    } ORDER, *PORDER;
    
    
    PORDER Root = NULL;     
    
    void AddRecord( void );
    void DeleteRecord( void );
    void ListRecord( void );
    void FreeRest( void );
    
    
    
    int main()
    {
       int option, artist;
    
    		do 
    	{	printf("\n===================================\n");
    		printf("\nWelcome to the Music Storage System\n");
    		printf("\n===================================\n\n\n");
    		printf("1-- Add New Album Record\n");
    		printf("2-- Remove Existing Album Record\n");
    		printf("3-- Display All Album Records\n");
    		printf("4-- Exit\n\n");
    		printf("Please select your option\n\n");
    		scanf("%d",&option);
    		switch (option)
    		{
    		case 1: {	do 
    						{
    							printf("\nEnter the Type of Album:\n");
    							printf("1-- Single Artist\n");
    							printf("2-- Multiple Artists\n");
    							scanf("\n%d",&artist);
    							switch (artist)
    									{
    										case 1: AddRecord(); main();
    										case 2: printf("\nThis system only supports albums created for single artists.\n");main();
    									}
    						}while (artist !=2);
    				}
    		case 2: DeleteRecord();
    		case 3: ListRecord();
    		case 4: break;
    		}
    	}while (option !=4);
    
    
       FreeRest();
    
       return( 0 );
    }
    
    
    void AddRecord( void )
    {
       char Name[sizeof(Root->Name)];
       char Album[sizeof(Root->Album)];
       int  Qty;
       int  Year;
       char trackTitle[50];
       char trackTime[50];
       int x, y;
       static int  Seq = 0;
       PORDER p;
    
       printf( "\n\nEnter artist's name, album's name, year and total number of tracks : \n");
       fflush( stdout );
    
       if ( scanf( "%30s%30s%d%d", Name, Album, &Year, &Qty) == 4 )
       {
    
    		for (x=0;x<Qty;x++)
    		{
    			printf("Enter track title : ");
    			scanf("%s",&trackTitle[x]);
    
    			printf("Enter track time : ");
    			scanf("%s",&trackTime[x]);
    		}
    
             p = malloc( sizeof( *p ) ); 
             if ( p == NULL )            
             {
                fprintf( stderr, "\nMemory allocation failed!\a\n" );
                exit( 1 );
             }
    
    
             strcpy( p->Name, Name );
    		 strcpy( p->Album, Album );
    
      		for (y=0;y<=Qty;y++)
    		{
    			p->trackTitle[x] = trackTitle[x];
    			p->trackTime[x] = trackTime[x];
    		}
    
             p->Qty = Qty;
    		 p->Year = Year;
             p->Req = ++Seq;  
    
             p->Next = Root;  
             Root = p;         
    
             printf( "\nRecord number %05d assigned\n", Seq );
    	   
       }
    }
    
    
    void DeleteRecord( void )
    {
       int  Seq;
       PORDER p, prev;
    
       printf( "\n\nEnter record number : " );
       fflush( stdout );
       if ( scanf( "%d", &Seq ) == 1 )
       {
    
          for ( p = Root, prev = NULL; p != NULL; p = p->Next )
          {
             if ( p->Req == Seq )
             {
                if ( prev == NULL )
                {
      
                   Root = p->Next;  
                }
                else
                {
      
                   prev->Next = p-> Next;
                }
                free( p );        
    
                printf( "\nRecord number %05d deleted\n", Seq );
                break;
             }
             prev = p;
          }
    
          if ( p == NULL )
          {
             printf( "\n\aRecord number %05d not found\n", Seq );
          }
       }
    }
    
    
    void ListRecord( void )
    {
       PORDER p;
       int z;
       int NO=1;
    
       printf( "\n\nListing of records currently in process...\n\n" );
    
       for ( p = Root; p != NULL; p = p->Next )
       {
          printf( "Record number: %05d, Artist Name: %s, Album Name: %s, Total %d Tracks Released in Year %d\n",
                  p->Req, p->Name, p->Album, p->Qty, p->Year);
    
      		for (z=0;z<=p->Qty;z++)
    		{
    			printf( "Track %d: %s \tDuration: %s\n", NO, p->trackTitle[z], p->trackTime[z]);
    			NO=NO+1;
    		}
    
       }
    
    }
    
    
    void FreeRest( void )
    {
       PORDER p;
    
       while( Root != NULL )
       {
          p = Root;
          Root = p->Next;
          free( p );
       }
    
    }

  2. #2
    ~viaxd() viaxd's Avatar
    Join Date
    Aug 2003
    Posts
    246
    i really can't test this right now, so don't believe everything i say

    Code:
       char Name[sizeof(Root->Name)];
       char Album[sizeof(Root->Album)];
    this is wrong, since Root points to NULL.

    Code:
    case 1: AddRecord(); main();
    case 2: printf("\nThis system only supports albums created for single artists.\n");main();
    Why are you calling main() ??? you can probably use break; or continue; there.

    Code:
    		for (x=0;x<Qty;x++)
    		{
    			printf("Enter track title : ");
    			scanf("%s",&trackTitle[x]);
    
    			printf("Enter track time : ");
    			scanf("%s",&trackTime[x]);
    		}
    no need for the for loop and no need for & here.

    and some other mistakes
    :wq

  3. #3
    Registered User
    Join Date
    Mar 2003
    Posts
    143
    Quite a lot of bad stuff here!
    To start with you need to use breaks in your switch statements. And its always a good
    idea to have a default case to catch the unwary. _Never_ recursively call main()
    Code:
      do {
        printf("\n===================================\n");
        printf("\nWelcome to the Music Storage System\n");
        printf("\n===================================\n\n\n");
        printf("1-- Add New Album Record\n");
        printf("2-- Remove Existing Album Record\n");
        printf("3-- Display All Album Records\n");
        printf("4-- Exit\n\n");
        printf("Please select your option\n\n");
        scanf("%d",&option);
        switch (option)
        {
          case 1: 
            AddRecord();
            break;
          case 2: 
            DeleteRecord();
            break;
          case 3: 
            ListRecord();
            break;
          case 4: 
            break;
          default:
            printf("invalid input\n");
            break;
        }
      }while (option !=4);
    You need 2-D arrays to store lists of strings. I also simplified the code so that you
    read input straight into the structure rather than having to copy it all:
    Code:
    typedef struct _order_      
    {
      char Name[31];
      char Album[31];
      int  Req;              
      int  Year;
      int  Qty;    
      char trackTitle[50][50];
      char trackTime[50][50];
      struct _order_  *Next;  
    } ORDER, *PORDER;
     /*..... */
    void AddRecord( void )
    {
      int x;
      static int  Seq = 0;
      PORDER p;
    
      p = malloc( sizeof( *p ) ); 
      if ( p == NULL ) {
        fprintf( stderr, "\nMemory allocation failed!\a\n" );
        exit( 1 );
      }
    
      printf( "\n\nEnter artist's name, album's name, year and total number of tracks : \n");
      fflush( stdout );
    
      if ( scanf( "%30s%30s%d%d", p->Name, p->Album, &p->Year, &p->Qty) == 4 ) {
        for ( x=0; x<p->Qty; x++ ) {
          printf("Enter track title : ");
          scanf("%s",&p->trackTitle[x]);
    
          printf("Enter track time : ");
          scanf("%s",&p->trackTime[x]);
        }
    
        p->Req = ++Seq;  
    
        p->Next = Root;  
        Root = p;         
    
        printf( "\nRecord number %05d assigned\n", Seq );
      }
      else {
        free(p);
      }
    }
    This also get around the problem where you were trying to copy strings using '='
    (ok you actually weren't but you should've been..or something...). Oh, and generally its
    a bad idea to use an identifier starting with a '_'. You might find yourself conflicting
    with a library function one day. There were a couple of loops where you were running
    off the end of where you wanted to be because you were using a (x=0; x<=MAX; x++)
    formulation instead of (x=0; x<MAX; x++).

    Other problems I'll leave you to fix:
    - albums are printed out in reverse order (by Req) which is just annoying
    - track listing doesn't always line up
    - scanf() isn't the best input function in the world and one of the problems is
    that I can't have band names or album titles with spaces in.
    - Need to add checking to make sure your arrays are not overflowing. (another
    reason for not using scanf() - use fgets() instead.
    - What about implementing track listing as a linked list?
    DavT
    -----------------------------------------------

  4. #4
    Registered User
    Join Date
    Jun 2004
    Posts
    277

    Thumbs up

    I have implemented alist that does everything you need, obviusly you will have to modify the kind of data it handles, but it will take at most 15 minutes, another thing, it is kinda wierd to declare all funtions as void, you never return anything, I think you could also avoid to call main recursively (I hope I spelled right ).

    Well here goes my code, just implemented...
    Code:
    //Simple Linked List
    
    #include<stdio.h>
    #include<stdlib.h>
    
    struct listNode {
    	char data;
    	struct listNode *nextPtr;
    	};
    
    typedef struct listNode LISTNODE;
    typedef LISTNODE *LISTNODEPTR;
    
    void insert(LISTNODEPTR *, char);
    char exclude(LISTNODEPTR *, char);
    int isEmpty(LISTNODEPTR);
    void printList(LISTNODEPTR);
    void instructions(void);
    
    int main(){
    	LISTNODEPTR startPtr = NULL;
    	int choice;
    	char item;
    	
    	instructions();/*Displays the Menu*/
    	printf("?");
    	scanf("%d",&choice);
    		while (choice !=3 ) {
    			switch(choice) {
    				case 1:
    					printf("Type a character: ");
    					scanf("\n%c",&item);
    					insert(&startPtr, item);
    					printList(startPtr);
    				break;
    				
    				case 2:
    				  if (!isEmpty(startPtr)) { 
    					printf("Type a character:");
    					scanf("\n%c",&item);
    					  
    					  if (exclude(&startPtr, item)) {
    						  printf("Removed %c", item);
    						  printList(startPtr);
    						  }
    					  	else
    							printf("%c not found \n", item);
    				  }
    				  else
    					  printf("Empty List");
    				  break;
    				
    				default :
    					printf("Invalid Choice");
    					instructions();
    					break;
    				}//switch
    			printf("?");
    			scanf("%d",&choice);
    		}
    	printf("end\n");
    	return 0;
    }//main
    
    /*Prints the Instructions*/
    void instructions( void ){
    	printf("Choose an Option:\n"
    	"1 to insert an element.\n"
    	"2 to remove an element.\n"
    	"3 to exit.\n");
    	}
    
    /*Insert a new value in the list*/
    void insert(LISTNODEPTR *sPtr, char value){
    	LISTNODEPTR newPtr, previousPtr, currentPtr;
    	
    	newPtr = malloc(sizeof(LISTNODE));
    		if (newPtr != NULL) {
    			newPtr->data = value;
    			newPtr->nextPtr = NULL;
    			previousPtr = NULL;
    			currentPtr = *sPtr;
    		
    			while (currentPtr != NULL && value > currentPtr->data){
    				previousPtr = currentPtr;
    				currentPtr = currentPtr->nextPtr;
    				}
    			if (previousPtr == NULL) {
    				newPtr->nextPtr = *sPtr;
    				*sPtr = newPtr;
    				}
    				else {
    					previousPtr->nextPtr = newPtr;
    					newPtr->nextPtr = currentPtr;
    				}				
    			}
    		else 
    			printf("%c not inserted. Not enough memmory\n", value);
    }
    
    /*Removes an Element of the List*/
    char exclude(LISTNODEPTR *sPtr, char value){
    	LISTNODEPTR previousPtr, currentPtr, tempPtr;
    	
    	if (value == (*sPtr)->data){
    		tempPtr = *sPtr;
    		*sPtr = (*sPtr)->nextPtr;
    		free(tempPtr);
    		return value;
    	}//if 
    	else {
    		previousPtr = *sPtr;
    		currentPtr = (*sPtr)->nextPtr;
    		
    		while (currentPtr != NULL && currentPtr->data != value){
    			previousPtr = currentPtr;
    			currentPtr = currentPtr->nextPtr;
    			}//while
    		if (currentPtr != NULL){
    			tempPtr = currentPtr;
    			previousPtr->nextPtr = currentPtr->nextPtr;
    			free(tempPtr);
    			return value;
    			} 
    		}//else
    	return '\0';
    }
    
    /*Returns 1 if empty list else retuns 0*/
    int isEmpty(LISTNODEPTR sPtr){
    	return sPtr == NULL;
    }
    
    /*Prints the List*/
    void printList(LISTNODEPTR currentPtr){
    	if (currentPtr == NULL)
    		printf("The List is Empty\n");
    	else {
    		printf("The is is:\n");
    		
    		while (currentPtr != NULL){
    			printf("%c --> ", currentPtr->data);
    			currentPtr = currentPtr->nextPtr;			
    		}
    	printf("NULL\n\n");
    	}
    }
    It MIGHT don't work (did it in a hurry) but at least you can have the idea of wich direction follow... If you can't understand any step just ask, good luck!

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. single linked list to double linked list (help)
    By Countfog in forum C Programming
    Replies: 8
    Last Post: 04-29-2008, 08:04 PM
  2. Adding directory/file names to a linked list
    By thoseion in forum C Programming
    Replies: 13
    Last Post: 12-08-2006, 01:13 PM
  3. Please Help - Problem with Compilers
    By toonlover in forum C++ Programming
    Replies: 5
    Last Post: 07-23-2005, 10:03 AM
  4. How can I traverse a huffman tree
    By carrja99 in forum C++ Programming
    Replies: 3
    Last Post: 04-28-2003, 05:46 PM
  5. Array, Linked List, or Binary Tree?
    By Unregistered in forum C Programming
    Replies: 6
    Last Post: 01-05-2002, 10:07 PM