Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // Insert any number at beginning of the linked list implementation
- #define _CRT_SECURE_NO_WARNINGS
- #include "stdlib.h"
- #include "stdio.h"
- struct Node { // define the struct type
- int data; // the Node struct is composed by firs part that contain the data as intiger
- struct Node* next; // the secondo part contain the adress of the next Node
- };
- struct Node* head; // global variable,can be accessed anywhere
- void Insert(int x) { // insert at the beginning
- struct Node* temp = malloc(sizeof(struct Node)); // alloc enough memory for a temp struct Node
- temp->data = x; // the data part of the Node contain the number that we want to insert at the beginning
- temp->next = head; //and put the adress of the old head in the next adress, it's like shifting to the right all the list
- head = temp; //now the new head is our inserted element
- }
- void Print() {
- struct Node* temp = head; //begin to print from the head, it's like the root of the list
- printf("List is : ");
- while (temp != NULL) { // while the adress of the next inside the current Node is not empty, print all the temp->data
- printf(" %d", temp->data);
- temp = temp->next;
- }
- printf("\n");
- }
- int main() {
- head = NULL; // empty list;
- printf("how many numbers?\n");
- int n ,i,x;
- scanf("%d", &n); //save inside a variable our number in input
- for (i = 0;i < n; i++) { // insert all the number in the beginning of the list
- printf("enter the number \n");
- scanf("%d", &x);
- Insert(x); //insert function
- Print();
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement