Question:

C++ help (Linked List and struct)...?

by  |  earlier

0 LIKES UnLike

struct ListNode

{

int data ;

ListNode *next ;

};

It's just the beginning of the code with a long linked list. My question is that how does the compiler know that what is "next"..for instance...the use for "next" after this is

int listLength(ListNode *head)

{

int count = 0 ;

ListNode *current = head ;

while (current != NULL)

{

count++ ;

current = current->next ;

}

return count ;

}

after the current is defined, how does the compiler know that "next" is really the next item in the list? Thank you for any help!

 Tags:

   Report

3 ANSWERS


  1. Hi,

    U tag ur last node as NULL. While loop keeps on checking the content of current until it is NULL. Compiller doesnt know any thing about Linked List, it is ur code which tells the next node.

    current = current->next ; This statement keeps on supplying address of next node. u remove this statement. Then curent will never change and while loop will never end.

    A linked list is like a train where each coach is linked to another. The only difference is coaches are linked one after another physically. But nodes in a linked list are saved at differnt places in memory. One node only contains the address of another node.

    What u do u alway keep the address of the first node of the linked List and tag the last node with a NULL. So that u could know the start and end of the list.

    Compiller doesnt help if u loose the address of the first node or forget to tag the last node.


  2. The compiler has no idea, it simply translates your code into Assembly (machine code). When run, that machine code by using the loop you posted above is able to jump from one memory address to another through pointers to memory locations in each LL node (the current = current->next; part) to eventually hit the end of the LL (the node with null pointer) while keeping track of how many hops it makes, then it returns the number of hops.

  3. I think, the current is a ListNode structure, that mean, the current has 2 parts: data: save the content, and the next - is a ListNode, save the address of the next item.

    after saving the code, press F7 to build, then press F10 to compile step- by -step, you can see how the compiler "know". ( click on the + to view more.)

Question Stats

Latest activity: earlier.
This question has 3 answers.

BECOME A GUIDE

Share your knowledge and help people by answering questions.