hello

How do I traverse & compare 2 linked lists that have different sizes without getting an error.

For example:

List1 -> 1 -> 4 -> 6
List2 -> 8 -> 3 -> 2 -> 8

// I will get an error the 4th time this loop runs
// because I will be comparing the 4th element of list2 (8) 
// to the non existant 4th element of list1 (does not exist);
//


while (list1 != NULL && list2 != NULL) {
           if (list1->data != list2->data) }
               // do sumthing
           }
}

I guess you can only compare what you have... right?

Therefore, list traversal w/ comparison should only be as long as your shortest list.

Another option could be to populate the shortest list with a sentinal value so that both lists would be of the same length.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.