Untitled
unknown
c_cpp
2 years ago
2.1 kB
7
Indexable
#include <stdio.h>
#include <stdlib.h>
// Node structure for the linked list
struct Node {
int data;
struct Node* next;
};
// Function to create a new node
struct Node* createNode(int data) {
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
newNode->data = data;
newNode->next = NULL;
return newNode;
}
// Function to append a new node to the end of the linked list
void append(struct Node** head, int data) {
struct Node* newNode = createNode(data);
if (*head == NULL) {
*head = newNode;
return;
}
struct Node* temp = *head;
while (temp->next != NULL) {
temp = temp->next;
}
temp->next = newNode;
}
// Function to perform bubble sort on the linked list
void bubbleSort(struct Node* head) {
int swapped;
struct Node* ptr1;
struct Node* lptr = NULL;
if (head == NULL)
return;
do {
swapped = 0;
ptr1 = head;
while (ptr1->next != lptr) {
if (ptr1->data > ptr1->next->data) {
// Swap the data of the two nodes
int temp = ptr1->data;
ptr1->data = ptr1->next->data;
ptr1->next->data = temp;
swapped = 1;
}
ptr1 = ptr1->next;
}
lptr = ptr1;
} while (swapped);
}
// Function to print the linked list
void printList(struct Node* head) {
struct Node* temp = head;
while (temp != NULL) {
printf("%d ", temp->data);
temp = temp->next;
}
printf("\n");
}
// Main function to test the bubble sort with linked list
int main() {
struct Node* head = NULL;
// Example data for the linked list
append(&head, 5);
append(&head, 2);
append(&head, 9);
append(&head, 1);
append(&head, 5);
printf("Original linked list: ");
printList(head);
bubbleSort(head);
printf("Linked list after bubble sort: ");
printList(head);
return 0;
}
/*
Original linked list: 5 2 9 1 5
Linked list after bubble sort: 1 2 5 5 9
*/Editor is loading...
Leave a Comment