|
Page 5 of 6
Search
This operation is similar to normal implementation as shown below.
node *search (node* start, int value) {
node* cur;
for (cur = start; cur != NULL; cur = cur->next) {
if (cur->number == value) return cur;
}
return NULL;
}
Delete Node
The next operation on a linked list is element deletion. The function
returns int value indicating if operation is successful. If the first element is deleted from the
linked list, the root must be modified to point to the second element,
or be set to NULL if there is no second element. Deletion of any element is similar to normal implementation. However, a node to be freed is moved to free list unlike in normal scenario where node is returned to operating system. Freed node is added to end of Free List as shown below
freeEnd->next = tmp;
freeEnd = tmp;
Full function implementation may look like following.
// Free a Node
int deletenode (node** stptr) {
node *tmp;
// Get Current Free Node
if ((*stptr) != NULL) {
tmp = (*stptr);
} else {
return 0;
}
if ((*stptr)->next == NULL) {
(*stptr) = NULL;
} else {
(*stptr) = (*stptr)->next;
}
// Freeing A Node - Move it to Free List
if (freeSt == NULL) {
freeSt = tmp;
freeEnd = tmp;
} else {
freeEnd->next = tmp;
freeEnd = tmp;
}
return 1;
}
Node Addition
The next operation on a linked list is element addition. The function
returns int value indicating if operation is successful. If the first element is added to the
linked list, the root must be modified to point to the this element. Addition of any element is similar to normal implementation. However, unlike requesting a node from operating system, a node from Free List is taken and added to program List.
node2badd = freeSt;
freeSt = freeSt->next;
Node Addition implementation may look like following.
// Allocate a Node
int addnode (node **stptr, int value) {
node* prevptr = NULL;
node* ptr = NULL;
node *node2badd;
// Check where to insert
for (ptr = *stptr; ptr != NULL; ptr = ptr->next) {
if (ptr->number > value) {
break;
} else if (ptr->number == value) {
return 0;
}
prevptr = ptr;
}
// Get Current Free Node
if (freeSt != NULL) {
node2badd = freeSt;
node2badd->number = value;
} else {
return 0;
}
if (freeSt->next == NULL) {
freeSt = freeEnd = NULL;
} else {
freeSt = freeSt->next;
}
if ((*stptr) == NULL) {
(*stptr) = node2badd;
(*stptr)->next = NULL;
} else {
node2badd->next = ptr;
prevptr->next = node2badd;
}
return 1;
}
After designing all operations, writing main function is somewhat simple. Please note that main function should call init_fl before any other operation. Partial code is shown below.
node *start2 = NULL;
node *start3 = NULL;
node *start5 = NULL;
init_fl ();
if (data%2 == 0) addnode(&start2, data);
else if (data%3 == 0) addnode(&start3, data);
else if (data%5 == 0) addnode(&start5, data);
|