Thread: linked list not working :(

  1. #1
    Registered User
    Join Date
    May 2004
    Posts
    37

    linked list not working :(

    this program reads from standard input, storing each character into a linked list, then prints out characters stored in the list, but with space character changed into underscore "_".
    Code:
    #include <stdio.h>
    #include <stdlib.h>
    
    typedef struct node nodeType;
    
    struct node
    {
      char name;
      nodeType *next;
    };
    
    nodeType*
    chinsert(nodeType* ptr,char c)
    {
      nodeType *p;
    
      nodeType *new = (nodeType *)(malloc(sizeof(struct node)));
      new->name = c;
      new->next = NULL;
    
      if(ptr==NULL)
        return new;
      
      else
      {
        for(p=ptr; p->next!=NULL; p=p->next);
        
        p->next= new;
    
        return ptr;
      }
    }
    
    void
    prnList(nodeType *ptr)
    {
      nodeType *n = ptr;
    
      printf("\n");
      
      while(n != NULL)
      {
        printf("%c",n->name);
        n = n->next;
      }
      
      printf("\n");
      
    }
    
    void
    prn(nodeType *ptr)
    {
      nodeType *n = ptr;
    
      while(n != NULL)
      {
        if(n->name == ' ')
          printf("%c",n->name='_');
    
        else
          printf("%c",n->name);
    
        n = n->next;
      }
    
      printf("\n");
    
    }
    
    void
    cleanUp(nodeType *ptr)
    {
      nodeType *n;
    
      while(ptr->next != NULL)
      {
     
        n = ptr->next;
        ptr->next = n->next;
        free(n);
      }
    
       n = ptr;
       free(n);
    }
    
    int
    main(int argc, char *argv[])
    {
      char c;
      nodeType *ptr = NULL;
    
      while((c=getchar())!=EOF)
      {
        ptr = chinsert(ptr,c);
      }
    
      prnList(ptr);
      prn(ptr);
      cleanUp(ptr);
    
      return 0;
    }
    can anyone see why this doesnt work?

  2. #2
    Registered User
    Join Date
    May 2004
    Posts
    37
    do i need a printf in the main?

  3. #3
    Registered User
    Join Date
    May 2004
    Posts
    37
    my mistake, it works

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. help! Placement of nodes in a Linked List
    By lostmyshadow in forum C Programming
    Replies: 6
    Last Post: 12-17-2007, 01:21 PM
  2. circular doubly linked list help
    By gunnerz in forum C++ Programming
    Replies: 5
    Last Post: 04-28-2007, 08:38 PM
  3. Adding directory/file names to a linked list
    By thoseion in forum C Programming
    Replies: 13
    Last Post: 12-08-2006, 01:13 PM
  4. Linked List Help
    By CJ7Mudrover in forum C Programming
    Replies: 9
    Last Post: 03-10-2004, 10:33 PM
  5. singly linked list
    By clarinetster in forum C Programming
    Replies: 2
    Last Post: 08-26-2001, 10:21 PM