-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathinsertion at end.c
62 lines (50 loc) · 1.19 KB
/
insertion at end.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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
// INSERTION AT END PROGRAM
#include <stdio.h>
#include <stdlib.h>
struct node
{
int data;
struct node *next;
};
void addLast(struct node **head, int val)
{
// create a new node
struct node *newNode = malloc(sizeof(struct node));
newNode->data = val;
newNode->next = NULL;
// if head is NULL, it is an empty list
if (*head == NULL)
*head = newNode;
// Otherwise, find the last node and add the newNode
else
{
struct node *lastNode = *head;
// last node's next address will be NULL.
while (lastNode->next != NULL)
{
lastNode = lastNode->next;
}
// add the newNode at the end of the linked list
lastNode->next = newNode;
}
}
void printList(struct node *head)
{
struct node *temp = head;
// iterate the entire linked list and print the data
while (temp != NULL)
{
printf("%d->", temp->data);
temp = temp->next;
}
printf("NULL\n");
}
int main()
{
struct node *head = NULL;
addLast(&head, 10);
addLast(&head, 20);
addLast(&head, 30);
printList(head);
return 0;
}