I want to insert several nodes into an empty singly-linked list. It's OK when I insert the first node. However, the fist node is replaced by the second node when I call the function
the first time using function ListInsert(), the variable newNode is at the memory unit 0x7fffffffdf50. And the second time calling function ListInsert(), *L = 0x7fffffffdf50, **L = {m_Data = first node data, m_nextNode = NULL}. but when I create the newNode, it is still at the memory unit 0x7fffffffdf50. If I set newNode = second node data, it actually replace the first node but not insert into the linked list
struct t_Node
{
struct t_Data m_Data;
struct t_Node *m_nextNode;
}
typedef struct Node* t_LinkedList;
void ListInsert(t_LinkedList* L, int position, struct t_Data newData)
{
if (!*L)
{
struct t_Node newNode;
newNode.m_Data = newData;
newNode.m_nextNode = NULL;
(*L) = &newNode;
}
/* first Node is not NULL */
else
{
t_LinkedList anIterator;
anIterator = (*L);
if (!(*anIterator).m_nextNode)
{
struct t_Node newNode;
newNode.m_Data = newData;
newNode.m_nextNode = NULL;
(*anIterator).m_nextNode = &newNode;
}
}
}
t_LinkedList aLinkedList;
aLinkedList = NULL;
ListInsert(&aLinkedList,1,data1);
ListInsert(&aLinkedList,2,data2);
I expect to insert the second node based on the singly linked list with one node but not to replace the first node, and to maintain the structure of the program.