-
Notifications
You must be signed in to change notification settings - Fork 0
/
07-04
113 lines (113 loc) · 2.39 KB
/
07-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
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
Node* head;
void Print(){
Node* copy = head;
if(copy == NULL){
printf("NULL");
return ;
}
while(copy->next != head){
printf("%d->", copy->data);
copy = copy->next;
}
printf("%d->", copy->data);
printf("%d\n", head->data);
return;
}
int GetLength(){
Node* copy = head;
if(copy == NULL){
printf("NULL");
return 0;
}
int len = 0;
while(copy->next != head){
len++;
copy = copy->next;
}
len++;
return len;
}
Node* GetLast(){
Node* copy = head;
if(copy == NULL){
printf("NULL");
return NULL;
}
while(copy->next != head){
printf("%d->", copy->data);
copy = copy->next;
}
return copy;
}
Node* Search(int target){
Node* copy = head; // A
if(copy == NULL){
printf("NULL");
return NULL;
}
//A->A
while(copy->next != head){ // A != A
if(copy->data == target){
return copy;
}
copy = copy->next;
}
return (copy->data == target ? copy : NULL);
}
int Insert(int data, int position){
int len = GetLength();
if(position < 0 or position > len){
return 0;
}
Node* newNode = (Node*)(malloc(sizeof(Node*)));
newNode->data = data;
newNode->next = NULL;
if(head == NULL){
head = newNode;
newNode->next = newNode;
return 1;
}
else if(position == 0){
newNode->next = head;
head = newNode;
Node* lastNode = GetLast();
lastNode->next = 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 or position >= len){
return 0;
}
if(head == NULL){
return 0;
}
else if(position == 0){
Node* toBeDeleted = head;
head = (head == head->next ? NULL : head->next);
Node* lastNode = GetLast();
if(lastNode != NULL){
lastNode->next = head;
}
free(toBeDeleted);
return 1;
}
Node* copy = head;
while(position - 1 > 0){
copy = copy->next;
position--;
}
Node* toBeDeleted = copy->next;
copy->next = copy->next->next;
free(toBeDeleted);
return 1;
}