forked from akij17/Data-Structures-in-Pure-C
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlinkedlist.c
99 lines (91 loc) · 2.76 KB
/
linkedlist.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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
//
// Created by Akshay on 10/28/2018.
//
#include <stdio.h>
#include <stdlib.h>
#include "linkedlist.h"
linkedList *newLinkedList(){
linkedList *llist = malloc(sizeof(linkedList));
llist->size = 0;
node *head = malloc(sizeof(node));
head->data = -777;
head->next = NULL;
llist->head = head;
llist->tail = malloc(sizeof(node));
llist->tail->next = NULL;
llist->tail->data = -888;
return llist;
}
int isEmpty_linkedList(linkedList llist){
if(llist.size == 0) return 1;
else return 0;
}
void insert_linkedList(linkedList *llist, int item, int position) {
if(position >= llist->size) position = 999;
if (llist->size == 0) {
node *newNode = malloc(sizeof(node));
newNode->data = item;
newNode->next = NULL;
llist->head->next = newNode;
llist->tail->next = newNode;
llist->size++;
} else {
//printf("Come here");
if (position == 0){
//printf("position0here");
node *temp = llist->head->next;
node *newNode = malloc(sizeof(node));
newNode->data = item;
newNode->next = temp;
llist->head->next = newNode;
llist->size++;
}else if(position == 999) {
printf("-2HERE");
//printf("positionENDhere");
node *newNode = malloc(sizeof(node));
newNode->data = item;
newNode->next = NULL;
llist->tail->next->next = newNode;
llist->tail->next = newNode;
llist->size++;
}
else {
node *current = llist->head;
//printf("positionRANDOMhere");
int count = position;
while(count>0){
current = current->next;
count--;
}
node *newNode = malloc(sizeof(node));
newNode->data = item;
newNode->next = current->next;
current->next = newNode;
llist->tail->next = newNode;
llist->size++;
}
}
}
void displayList_linkedList(linkedList lList){
printf("Linked List Size: %d\n", lList.size);
printf("Contents of linked list: ");
node *current = lList.head;
current = current->next;
while(current!=NULL){
printf("%d -> ", current->data);
current = current->next;
}
}
void delete_linkedList(linkedList *ll, int pos){
if(pos < ll->size) {
int count = pos;
node *current = ll->head;
while (count > 0) {
current = current->next;
count--;
}
current->next = current->next->next;
ll->size--;
}
else printf("Invalid position entered");
}