travesing a linked list

This is a discussion on travesing a linked list within the C Programming forums, part of the General Programming Boards category; Hi all, How do you find a node that contain a certain info and then return only one member of ...

  1. #1
    Unregistered
    Guest

    travesing a linked list

    Hi all,
    How do you find a node that contain a certain info and then return only one member of the structure? Thanks

  2. #2
    Mayor of Awesometown Govtcheez's Avatar
    Join Date
    Aug 2001
    Location
    MI
    Posts
    8,825
    Walk down the list until you find the node with the stuff you want in it, and return the member that you need...

  3. #3
    End Of Line Hammer's Avatar
    Join Date
    Apr 2002
    Posts
    6,231
    When all else fails, read the instructions.
    If you're posting code, use code tags: [code] /* insert code here */ [/code]

  4. #4
    Code Goddess Prelude's Avatar
    Join Date
    Sep 2001
    Posts
    9,796
    Code:
    int searchList ( struct node *list, struct node *find )
    {
      struct node *iter;
      for ( iter = list; iter != NULL; iter = iter->next )
        if ( iter->item == find->item )
          return iter->item;
      return NOT_FOUND;
    }
    This assumes that the item in the structure is an int, but it can be anything you want as long as you change the comparison accordingly. Start at the root of the list and traverse through the next pointers until the item of the iterator node and the node being searched for match. If the node to be searched for is not in the list, stop at the end and return a NOT_FOUND macro. I defined it like so:
    Code:
    #define NOT_FOUND -1
    Also make sure that the value for NOT_FOUND is an invalid value for a node in the list or you won't know whether or not you actually found the node.

    -Prelude
    My best code is written with the delete key.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Following CTools
    By EstateMatt in forum C Programming
    Replies: 5
    Last Post: 06-26-2008, 10:10 AM
  2. Reverse function for linked list
    By Brigs76 in forum C++ Programming
    Replies: 1
    Last Post: 10-25-2006, 10:01 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. Template Class for Linked List
    By pecymanski in forum C++ Programming
    Replies: 2
    Last Post: 12-04-2001, 08:07 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