| Linked List Implementation in ASIC - ANSI C |
|
|
|
| Written by SVTechie | ||||||||
Page 3 of 6 Element Addition Adding an element in a linked list is somewhat complicated. Adding an element to the linked list combines the operation of searching and the new operation of insertion. The first section of code searches if this number already exists or not. If number is already in the list, function returns without doing anything. Next, function looks for place where number can be inserted. The pointer prevptr points to the element having number less than the number to be inserted and the current pointer ptr points to the element having number greater than the number to be inserted. In case if this number to be inserted at start of List, prevptr will point to NULL. Similarly, if the number is greater than all the numbers on the list, then ptr will be NULL. In the case that the list is empty, both pointers will be NULL.
node *addnode (node* start, int value) { node* prevptr = NULL; node* ptr = NULL;
node* node2badd, cur; // Check where to insert for (ptr = start; ptr != NULL; ptr = ptr->next) { if (ptr->number > value) { break; } else if (ptr->number == value) { return start; }
prevptr = ptr; } // Create new node if ((node2badd = malloc(sizeof(node))) == NULL) { perror ("Can not allocate node\n"); exit(1); } node2badd->number = value; node2badd->next = NULL; // Add Node to the list if (prevptr == NULL) {
// Start of List or empty list node2badd->next = ptr; } else { node2badd->next = ptr; prevptr->next = node2badd; } return start;
} Once Linked List operations are designed and coded, rest of programming is relatively simple. Since 3 lists are required, there are three start pointers, one for each list. Symbolic code is shown below.
typedef struct node_def {
int number;
struct node_def *next;
} node; // Start Pointer node* startptr2; startptr3, startptr5;
Get_Next_Number value; if_divisible_by_2, startptr2 = addnode (startptr2, value); if_divisible_by_3, startptr3 = addnode (startptr3, value); if_divisible_by_5, startptr5 = addnode (startptr5, value); Perform_Next_Op_As_Required Above code is just symbolic and to show how to use Link List functions. Ofcourse, any real code will be dealing with lots of things apart from linked list alone and is not presented for sake of brevity.
|
||||||||
| Last Updated ( Saturday, 06 May 2006 ) | ||||||||
| < Prev | Next > |
|---|


Articles 

