I am working on an assignment, and need to write a function to add a new node to the tail of a linked list. My code so far is as follows.
As you can see, it is supposed to basically create a linked list of even numbers from 2 to 20, and created a linked list by adding the nodes onto the end of the list. I know how to do this, I just don't know how to put it into code.Code:#include <stdio.h> #include <stdlib.h> typedef struct IntNode { int data; struct IntNode *next; } IntNode; typedef struct List { IntNode *head; } List; void Add_to_Tail(List *list, List *newnode); IntNode *New_Node(int n); int main() { int i=0; List myList = {NULL}; for(i=1; i<=10; i++) { IntNode* n=New_Node(i*2); Add_to_Tail(&myList, n); } Print_List(&myList); Free_List(&myList); return 0; } IntNode *New_Node(int n){ IntNode *temp; temp = malloc(sizeof(IntNode)); temp->data = n; } void Add_to_Tail(List *list, List *newnode){ }
I know that my Add_to_Tail needs to do the following:
- Detect if node = 1st node, i.e. if the list is empty
- If not first node, use next ptr to find the end of the list
- Update the old next ptr to point to the new node
- ???
Any help converting this to code is greatly appreciated as always. Thanks.