Thread: FAQ lists and searches (C)

Hybrid View

Previous Post Previous Post   Next Post Next Post
  1. #1
    Registered User
    Join Date
    Sep 2001
    Posts
    752
    Linked list searches are all about loops really.

    Start with the first element.
    Break if you're pointing at the element you need.
    Repeat to the next element.

    Usually the only error condition is if you reach the end of the list, which is taken care of easily enough by breaking if your pointer is NULL.

    Assuming that list is a node * which points at the first element, and p is just a temporary node *, every search is gonna look something like this...
    Code:
    for (p = list; p != NULL; p = p -> next)
    {
     if (p -> info == searchVal) break;
    }
    After this bit of code, p will either have escaped the loop because it reached the end of the list (p == NULL), in which case you know searchVal is not in the list, or it will have escaped the loop because p points at a node, the content of which is searchval (p -> info == searchVal). So, the contents of p are very useful.

    p = p -> next
    is the code that steps from one node to the next. With a normal linked list however, you must understand that whatever node you are pointing at, you don't have any way of accessing information for the previous node. This becomes an issue when inserting nodes, circumvented by the use of two node pointers, the use of a node pointer pointer, or code that looks like this...
    Code:
    if (p -> next -> info == searchVal)
    Last edited by QuestionC; 10-31-2001 at 08:08 PM.
    Callou collei we'll code the way
    Of prime numbers and pings!

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Unknown memory leak with linked lists...
    By RaDeuX in forum C Programming
    Replies: 6
    Last Post: 12-07-2008, 04:09 AM
  2. Singly-linked lists and memory loss (valgrind report)
    By Nazgulled in forum C Programming
    Replies: 5
    Last Post: 03-11-2008, 06:45 AM
  3. Linked Lists in C++
    By cworld in forum C++ Programming
    Replies: 2
    Last Post: 04-16-2002, 07:28 PM
  4. lists and searches
    By Unregistered in forum C Programming
    Replies: 3
    Last Post: 10-31-2001, 08:04 PM