### Inserting in Linked List

Okay, I'd like to get some help in analyzing the insertion of linked lists. Let's say, your insert() inserts the newly created node at the "tail" of the list. I get the part wherein you set the first-ever created node as the origin node of the list, but what I can't understand is "what if it's not the origin first node in the list"?

From the code below, I can't get how the else part works. Like, when I used the tmpNode earlier, did it "connect" all of the nodes as it traversed through the list? If that is so, then shouldn't the code below work? Like, it doesn't connect the newly nth node to the first node, that's why when I display the contents of the list, only the first one appears.

 ``123456`` `````` ... if(listA == tmpNode){ listA = newNode; } else { tmpNode->next = newNode; }``````

Code below malfunctions, by the way. Can't get it to insert more than 1 entry.

 ``123456789101112131415161718192021`` ``````void insertData(int y){ struct Node *newNode, *tmpNode = listA; while(tmpNode){ tmpNode = tmpNode->next; } if((newNode = (struct Node *)malloc(sizeof(struct Node))) == NULL){ printf("Memory allocation failed."); getch(); return; } newNode->data = y; newNode->next = NULL; if(listA == tmpNode){ listA = newNode; } else { tmpNode->next = newNode; } }``````

EDIT: Forgot to mention, this is in C.
Last edited on
 ``1234567891011121314151617`` ``````_Bool InsertLast( struct Node **start, int value ) { struct Node *newNode = ( struct Node * ) malloc( sizeof( struct Node ) ); if ( !newNode ) return 0; newNode->next = NULL; newNode->data = value; struct Node *target = *start; while ( target && target->next != NULL ) ) target = target->next; if ( !target ) *start = newNode; else target->next = newNode; return 1; } ``````
Thanks, but unfortunately, this is in C... although, I do get the logic in your code (well, somehow). But I hope I'm not asking for too much, but I'd like to know how this insertion really works (like how are the nodes really connected by the pointers)
Last edited on
 @riechan Thanks, but unfortunately, this is in C...

And what is the problem? I showed a C code.
A similar function

 ``12345678910111213`` ``````_Bool InsertFirst( struct Node **start, int value ) { struct Node *newNode = ( struct Node * ) malloc( sizeof( struct Node ) ); if ( !newNode ) return 0; newNode->next = start; newNode->data = value; *start = newNode; return 1; } ``````
Topic archived. No new replies allowed.