singly linked list

This is a discussion on singly linked list within the C Programming forums, part of the General Programming Boards category; I am building a phone book and require the use of pointers to do so. My issue is there a ...

  1. #1
    Registered User
    Join Date
    Jun 2010
    Posts
    3

    Question singly linked list

    I am building a phone book and require the use of pointers to do so. My issue is there a way to add nodes from user input without hard lining the code myself in?
    Code:
    struct pb
    {
        int* data;
        char* first;
        char* last;
        char* phone;
        struct pb* next;
    };
    
    pb* e1 = NULL;
    pb* e2 = NULL;
    pb* e3 = NULL;
    .........
    
    e1 = malloc(sizeof(struct pb));
    e2 = malloc(sizeof(struct pb));
    e3 = malloc(sizeof(struct pb));
    ..........
    
    
    e1->data = 1;
    e1->next = e2;
    
    e2->data = 2;
    e2->next = e3;
    
    e3->data = 3;
    e3->next = e4;
    
    .......
    i am sure there is an easier and simplier way to do this, but i can not figure it out. Please advise

  2. #2
    Registered User claudiu's Avatar
    Join Date
    Feb 2010
    Location
    London, United Kingdom
    Posts
    2,094
    You keep a node that is the head of the list. Then you use a pointer as an iterator to traverse the list to the end:

    Code:
    struct pb *iterator;
    struct pb *new_node = malloc(sizeof(struct pb));
    for(iterator = head;iterator->next != NULL;iterator = iterator->next);
    
    /* now after that for iterator is the last element so we can insert */
    iterator->next = new_node;
    new_node->next = NULL;
    1. Get rid of gets(). Never ever ever use it again. Replace it with fgets() and use that instead.
    2. Get rid of void main and replace it with int main(void) and return 0 at the end of the function.
    3. Get rid of conio.h and other antiquated DOS crap headers.
    4. Don't cast the return value of malloc, even if you always always always make sure that stdlib.h is included.

  3. #3
    Registered User
    Join Date
    Jun 2010
    Posts
    3
    thank you very much. I was thinking of a while loop but could not quite get it right

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Anyone good with linked list.....I am not....
    By chadsxe in forum C++ Programming
    Replies: 11
    Last Post: 11-10-2005, 01:48 PM
  2. Replies: 6
    Last Post: 03-02-2005, 01:45 AM
  3. How can I traverse a huffman tree
    By carrja99 in forum C++ Programming
    Replies: 3
    Last Post: 04-28-2003, 05:46 PM
  4. Contest Results - May 27, 2002
    By ygfperson in forum A Brief History of Cprogramming.com
    Replies: 18
    Last Post: 06-18-2002, 01:27 PM
  5. singly linked list
    By clarinetster in forum C Programming
    Replies: 2
    Last Post: 08-26-2001, 10:21 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21