-
Notifications
You must be signed in to change notification settings - Fork 0
/
linked.c
121 lines (102 loc) · 2.47 KB
/
linked.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
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
#include <stdio.h>
#include <stdlib.h>
struct Node{
int data;
struct Node* next;
};
void printList(struct Node* firstNode){
struct Node* temp;
temp = firstNode;
printf("[ ");
while(temp!=NULL){
printf("%d ",temp->data);
temp = temp->next;
}
printf("]");
}
struct Node* arrayToList(int arr[],int length){
if(length > 0){
struct Node* next = NULL;
struct Node* first= NULL;
for(int i = 0; i<length; i++){
struct Node* temp;
if(next == NULL){
temp = (struct Node*) malloc(sizeof(struct Node));
first = temp;
}
else{
temp = next;
}
temp->data = arr[i];
if(i!=length-1){
next = (struct Node*) malloc(sizeof(struct Node));
temp->next = next;
}
else{
next = NULL;
}
}
return first;
}
else{
return NULL;
}
}
int getLength(struct Node* list){
int len = 0;
struct Node* temp = list;
while(temp != NULL){
len++;
temp = temp->next;
}
return len;
}
void push(struct Node** list, int val){
struct Node* newNode;
newNode = (struct Node*) malloc(sizeof(struct Node));
newNode->next = *list;
newNode->data = val;
*list=newNode;
return;
}
void append(struct Node* list, int val){
struct Node* last = list;
struct Node* newNode = (struct Node*) malloc(sizeof(struct Node));
while(last->next!=NULL){
last = last->next;
}
newNode->data = val;
newNode->next=NULL;
last->next=newNode;
return;
}
void insertAt(struct Node** list, int val, int pos){
int length = getLength(*list);
if(pos<0 || pos>=length){
printf("invalid input for 'pos' variable");
}
else if(pos==0){
push(list,val);
}
else if(pos==length-1){
append(*list,val);
}
else{
//in between
struct Node* prev = *list;
for(int i=0;i<pos-1;i++){
prev = prev->next;
}
struct Node* newNode = (struct Node*) malloc(sizeof(struct Node));
newNode->data = val;
newNode->next = prev->next;
prev->next = newNode;
}
}
int main(){
int myArray[6] = {1,2,3,4,5,6};
struct Node* linkedList = arrayToList(myArray,sizeof(myArray) / sizeof(int));
insertAt(&linkedList,2,0);
printList(linkedList);
return 0;
}