Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include<stdio.h>
- #include<cs50.h>
- #include<stdlib.h>
- struct linkedList
- {
- int data;
- struct linkedList *next;
- };
- typedef struct linkedList *node; //define node as pointer of data type struct LinkedList
- node createNode() // returns type node, name of function is createNode, takes 0 arguments
- {
- node temp; //declare a node
- temp = (node)malloc(sizeof(struct linkedList)); //allocate memory using malloc
- temp -> next = NULL; //make next point to NULL
- return temp; //return the new node
- }
- node addNode (node head, int value)
- {
- node temp, p; //declare two nodes temp and p
- temp = createNode();//createNode will return a new node with data = value and next pointing to NULL
- temp -> data = value; //add element's value to data part of node
- if (head == NULL)
- {
- head = temp; // when linked list is empty
- }
- else
- {
- p = head; // assign head to p
- while (p->next != NULL)
- {
- p = p->next; // taverse the list until p is the last node. The last node always points to NULL.
- }
- p -> next = temp; //point the previous last node to the node created
- }
- return head;
- }
- int main (void)
- {
- //creates first node
- node new = createNode();
- //adds a node with the value 6
- addNode(new, 6);
- //add some more nodes
- for (int i=0; i<5; i++)
- {
- addNode(new, i);
- }
- //traverse the list
- node p;
- p = new;
- while (p != NULL)
- {
- p = p -> next;
- printf("%i\n", new ->data);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement