Advertisemen
Decided to make my own linked list in C
#include <stdio.h>
#include <stdlib.h>
struct node
{
int value;
struct node *next;
};
void printList( struct node *root )
{
struct node *conductor;
conductor = root;
if (conductor != NULL)
{
printf("%d",conductor->value);
while (conductor->next != NULL)
{
conductor = conductor->next;
printf(" ===> %d",conductor->value);
}
printf("\n");
}
}
void insert( struct node **root, int value )
{
struct node *conductor,*insert,*prevNode;
conductor = *root;
prevNode = NULL;
if (conductor != NULL)
{
while (conductor != NULL && value > conductor->value)
{
prevNode = conductor;
conductor = conductor->next;
}
//create a new node to insert
insert = (struct node*) malloc( sizeof(struct node) );
insert->value = value;
insert->next = conductor;
if (prevNode != NULL)
prevNode->next = insert;
else
{
//use conductor as temp
conductor = *root;
*root = insert;
insert = conductor;
}
}
else
{
*root = (struct node*) malloc( sizeof(struct node) );
(*root)->value = value;
(*root)->next = NULL;
}
}
void destroy( struct node **root, int value )
{
struct node *conductor,*prevNode;
conductor = *root;
prevNode = NULL;
while (conductor != NULL)
{
if (conductor->value == value)
break;
prevNode = conductor;
conductor = conductor->next;
}
if (conductor == NULL) //nothing deleted
return;
//delete element
if (prevNode != NULL)
prevNode->next = conductor->next;
else
//use conductor as temp
*root = (*root)->next;
}
int main()
{
struct node *root = NULL;
insert(&root,3);
insert(&root,2);
insert(&root,5);
insert(&root,1);
destroy(&root,1);
printList(root);
return 0;
}
Advertisemen
Tidak ada komentar:
Posting Komentar