|
| 1 | +#include <stdio.h> |
| 2 | +#include <string.h> |
| 3 | +#include <math.h> |
| 4 | +#include <stdlib.h> |
| 5 | +struct node{ |
| 6 | + int data; |
| 7 | + struct node *next; |
| 8 | +}; |
| 9 | + |
| 10 | +//Represent the head and tail of the singly linked list |
| 11 | +struct node *head, *tail = NULL; |
| 12 | + |
| 13 | +//addNode() will add a new node to the list |
| 14 | +void addNode(int data) { |
| 15 | + //Create a new node |
| 16 | + struct node *newNode = (struct node * )malloc( sizeof(struct node)); |
| 17 | + newNode->data = data; |
| 18 | + newNode->next = NULL; |
| 19 | + |
| 20 | + //Checks if the list is empty |
| 21 | + if(head == NULL) { |
| 22 | + //If list is empty, both head and tail will point to new node |
| 23 | + head = newNode; |
| 24 | + tail = newNode; |
| 25 | + } |
| 26 | + else { |
| 27 | + //newNode will be added after tail such that tail's next will point to newNode |
| 28 | + tail->next = newNode; |
| 29 | + //newNode will become new tail of the list |
| 30 | + tail = newNode; |
| 31 | + } |
| 32 | +} |
| 33 | +void sortList() { |
| 34 | + //Node current will point to head |
| 35 | + struct node *current = head, *index = NULL; |
| 36 | + int temp; |
| 37 | + |
| 38 | + if(head == NULL) { |
| 39 | + return; |
| 40 | + } |
| 41 | + else { |
| 42 | + while(current != NULL) { |
| 43 | + //Node index will point to node next to current |
| 44 | + index = current->next; |
| 45 | + |
| 46 | + while(index != NULL) { |
| 47 | + //If current node's data is greater than index's node data, swap the data between them |
| 48 | + if(current->data > index->data) { |
| 49 | + temp = current->data; |
| 50 | + current->data = index->data; |
| 51 | + index->data = temp; |
| 52 | + } |
| 53 | + index = index->next; |
| 54 | + } |
| 55 | + current = current->next; |
| 56 | + } |
| 57 | + } |
| 58 | + } |
| 59 | + |
| 60 | +//display() will display all the nodes present in the list |
| 61 | +void display() { |
| 62 | + //Node current will point to head |
| 63 | + struct node *current = head; |
| 64 | + if(head == NULL) { |
| 65 | + printf("List is empty \n"); |
| 66 | + return; |
| 67 | + } |
| 68 | + while(current != NULL) { |
| 69 | + //Prints each node by incrementing pointer |
| 70 | + printf("%d ", current->data); |
| 71 | + current = current->next; |
| 72 | + } |
| 73 | + printf("\n"); |
| 74 | +} |
| 75 | + |
| 76 | +int main() { |
| 77 | + |
| 78 | + int n,m,data; |
| 79 | + scanf("%d%d",&n,&m); |
| 80 | + for(int i=0;i<n+m;i++) |
| 81 | + { |
| 82 | + scanf("%d",&data); |
| 83 | + addNode(data); |
| 84 | + } |
| 85 | + sortList(); |
| 86 | + display(); |
| 87 | + |
| 88 | + return 0; |
| 89 | +} |
0 commit comments