-
Notifications
You must be signed in to change notification settings - Fork 1
/
linked_list_insert_el_at_beginning.c
44 lines (36 loc) · 1.15 KB
/
linked_list_insert_el_at_beginning.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
#include<stdlib.h>
#include<stdio.h>
struct Node{
int data; // hold the data in the node
struct Node* next; // pointer to the node
};
struct Node* head;
void Insert(int x){
struct Node* temp = (struct Node*)malloc(sizeof(struct Node)); // create a new node
temp->data = x; // asign x as the node's data
temp->next = head; // link the element to the next element in the list or NULL if the element is the only element in the list
head = temp; // make the current element's address the head node(beginning of list)
}
void Print(){
struct Node* temp = head;
printf("List is: ");
while(temp != NULL){ // until there are untraversed elements in the list
printf(" %d", temp->data); // print the element
temp = temp->next; // move on to the next element
}
printf("\n");
}
// TEST>>>>NOT PART OF IMPLEMENTATION
int main(){
head = NULL; // empty list
printf("How many numbers will the list consist of?\n");
int n,i, x;
scanf("%d", &n);
for(i = 0; i < n; i++ ){
printf("Enter the number for index %d\n", i);
scanf("%d", &x);
Insert(x);
Print();
}
return 0;
}