Last active
June 9, 2020 18:20
-
-
Save AZagatti/67e8383788eb7d009f5e5ad45966320a to your computer and use it in GitHub Desktop.
Linked List
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include<stdio.h> | |
#include<stdlib.h> | |
struct Node { | |
int data; | |
struct Node *next; | |
}; | |
void printList(struct Node *start) { | |
struct Node *temp = start; | |
printf("\n"); | |
while (temp!=NULL) { | |
printf("%d ", temp->data); | |
temp = temp->next; | |
} | |
} | |
void printInt(void *n) { | |
printf(" %d", *(int *)n); | |
} | |
void swap(struct Node *a, struct Node *b) { | |
int temp = a->data; | |
a->data = b->data; | |
b->data = temp; | |
} | |
void bubbleSort(struct Node *start, int invert) { | |
int swapped, i; | |
struct Node *ptr1; | |
struct Node *lptr = NULL; | |
if (start == NULL) | |
return; | |
do { | |
swapped = 0; | |
ptr1 = start; | |
while (ptr1->next != lptr) { | |
if (invert == 1) { | |
if (ptr1->data < ptr1->next->data) { | |
swap(ptr1, ptr1->next); | |
swapped = 1; | |
} | |
} else { | |
if (ptr1->data > ptr1->next->data) { | |
swap(ptr1, ptr1->next); | |
swapped = 1; | |
} | |
} | |
ptr1 = ptr1->next; | |
} | |
lptr = ptr1; | |
} while (swapped); | |
} | |
void push(struct Node **start_ref, int data) { | |
struct Node *ptr1 = (struct Node*)malloc(sizeof(struct Node)); | |
ptr1->data = data; | |
ptr1->next = *start_ref; | |
*start_ref = ptr1; | |
} | |
void deleteNode(struct Node **head_ref, int key) { | |
struct Node* temp = *head_ref, *prev; | |
if (temp != NULL && temp->data == key) { | |
*head_ref = temp->next; | |
free(temp); | |
return; | |
} | |
while (temp != NULL && temp->data != key) { | |
prev = temp; | |
temp = temp->next; | |
} | |
if (temp == NULL) return; | |
prev->next = temp->next; | |
free(temp); | |
} | |
void insertPos(struct Node **current, int pos, int data) { | |
if (pos < 1 || pos > 10 + 1) | |
printf("Posição inválida!"); | |
else { | |
while (pos--) { | |
if (pos == 0) { | |
push(current, data); | |
} | |
else | |
current = &(*current)->next; | |
} | |
} | |
} | |
int main() { | |
struct Node *start = NULL; | |
int arr[] = {10, 5, 7, 4, 2, 3, 6, 8, 9, 1}, i; | |
for (i = 9; i >= 0; i--) { | |
push(&start, arr[i]); | |
} | |
printf("Created integer linked list is \n"); | |
bubbleSort(start, 0); | |
printList(start); | |
deleteNode(&start, 8); | |
printList(start); | |
insertPos(&start, 5, 8); | |
printList(start); | |
bubbleSort(start, 1); | |
printList(start); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment