-
Notifications
You must be signed in to change notification settings - Fork 0
/
03-04
97 lines (97 loc) · 2.02 KB
/
03-04
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
struct Node{
int data;
Node* next;
};
Node* head;
void print(){
if(head == NULL){
printf("NULL");
return ;
}
Node* copy = head;
Node* FirstNode = head;
while(copy->next != FirstNode){
printf("%d->", copy.data);
copy = copy.next;
}
printf("%d->", copy.data);
printf("%d", head.data);
}
int getLength(){
if(head == NULL){
return 0;
}
int len = 0;
Node* FirstNode = head;
Node* copy = head;
while(copy->next != FirstNode){
len++;
copy = copy.next;
}
return len + 1;
}
int insert(int data, int position){
int len = getLength();
if(position < 0 || position > len){
return 0;
}
Node* newNode = (Node*)(malloc(sizeof(Node)));
newNode.data = data;
newNode.next = NULL;
if(head == NULL || position == 0){
newNode.next = head;
head = newNode;
return 1;
}
Node* copy = head;
while(position - 1 > 0){
copy = copy.next;
position--;
}
newNode->next = copy->next;
copy->next = newNode;
return 1;
}
int delete(int position){
int len = getLength();
if(position < 0 || position > len){
return 0;
}
if(head == NULL || position == len){
return 0;
}
else if(position == 0){
Node* toBeDeleted = head;
head = head->next;
free(toBeDeleted);
return 1;
}
else if(len == 1 && pos == 0){
Node* toBeDeleted = head;
free(toBeDeleted);
head = NULL;
return 1;
}
Node* copy = head;
while(position - 1 > 0){ // 1-1 > 0
copy = copy.next;
position--;
}
Node* toBeDeleted = copy->next;
copy->next = copy->next->next;
free(toBeDeleted);
return 1;
}
Node* Search(int Target){
if(head == NULL){
return NULL;
}
Node* copy = head;
Node* FirstNode = head;
while(copy->next != FirstNode){
if(copy.data == Target){
return copy;
}
copy = copy.next;
}
}