Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>I usually try to leave the head and tail NULL until an element is inserted, rather than try to detect an empty node all over the place. Included is an example of a very simple linked list I use. Note that this version is for microcontrollers so I malloc/free the memory outside the list functions (sometimes from a preallocated node pool):</p> <pre><code>struct ListNodeStruct { struct ListNodeStruct* Next; int Value; }; typedef struct ListNodeStruct ListNode; struct ListStruct { ListNode* Head; ListNode* Tail; int Count; }; typedef struct ListStruct List; List CreateList() //creates a new List { List R; R.Head = NULL; R.Tail = NULL; R.Count = 0; return(R); } void ListInsertFirst(List* L, ListNode* V) //insert the object at the start of the list { V-&gt;Next = L-&gt;Head; L-&gt;Head = V; if (L-&gt;Count == 0) L-&gt;Tail = V; L-&gt;Count ++; } void ListInsertLast(List* L, ListNode* V) //insert the object at the end of the list { V-&gt;Next = NULL; if (L-&gt;Tail) L-&gt;Tail-&gt;Next = V; else L-&gt;Head = V; L-&gt;Tail = V; L-&gt;Count++; } ListNode* ListRemoveFirst(List* L) //remove the first object in the list (no memory is freed) { ListNode* R = L-&gt;Head; if (L-&gt;Head == NULL) return(R); L-&gt;Head = L-&gt;Head-&gt;Next; L-&gt;Count--; if (L-&gt;Count == 0) L-&gt;Tail = L-&gt;Head; return(R); } </code></pre> <p>Specific to your code, some problems can be avoided when you treat the object as a black box except for the functions that are <em>allowed</em> to see inside. Specifically, the beginning of your main function as well as line 69 directly manipulates the list members. I usually try to have a function dedicated to initializing the object, because you will have to do this again in many places as you use lists.</p> <p>On line 54, you push a pointer to a string literal into your structure. This pointer is only valid on the current stack frame, meaning when the function exits this pointer no longer will contain "EMPTY\0". You should call a malloc and store it there, and don't forget to free. Also note that C automatically null-terminates string literals so you don't need the \0 at the end.</p> <p>Finally, the reason it might not be iterating properly in the print function is because you are starting your print iterator at the tail and not the head. </p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload