106 lines
1.9 KiB
C
106 lines
1.9 KiB
C
|
#include <stdio.h>
|
||
|
#include <stdlib.h>
|
||
|
|
||
|
typedef struct node
|
||
|
{
|
||
|
char Character;
|
||
|
struct node *Next;
|
||
|
}node;
|
||
|
|
||
|
node *alloc_node(char c, node *Next)
|
||
|
{
|
||
|
node *NewNode = malloc(sizeof(node));
|
||
|
NewNode->Character = c;
|
||
|
NewNode->Next = Next;
|
||
|
|
||
|
return NewNode;
|
||
|
}
|
||
|
|
||
|
// NOTE: adds an element to the beginning
|
||
|
void list_add(node **Head, char c)
|
||
|
{
|
||
|
// TODO: implement this
|
||
|
node *NewNode = alloc_node(c, *Head);
|
||
|
*Head = NewNode;
|
||
|
}
|
||
|
|
||
|
// NOTE: inserts after a specific node
|
||
|
void list_insert_after(node *Node, char c)
|
||
|
{
|
||
|
// TODO: implement this
|
||
|
node *NewNode = alloc_node(c, Node->Next);
|
||
|
Node->Next = NewNode;
|
||
|
}
|
||
|
|
||
|
// NOTE: get's a node with the specified character
|
||
|
node *list_get(node **Head, char c)
|
||
|
{
|
||
|
// TODO: implement this
|
||
|
node *Result;
|
||
|
for(node *Iter = *Head; Iter; Iter = Iter->Next)
|
||
|
{
|
||
|
if(Iter->Character == c)
|
||
|
{
|
||
|
Result = Iter;
|
||
|
break;
|
||
|
}
|
||
|
}
|
||
|
return Result;
|
||
|
}
|
||
|
|
||
|
// NOTE: removes a specific node from the list
|
||
|
void list_remove(node **Head, node *Node)
|
||
|
{
|
||
|
// TODO: implement this
|
||
|
// Find prev node
|
||
|
node *Prev = 0;
|
||
|
for(node *Iter = *Head; Iter; Iter = Iter->Next)
|
||
|
{
|
||
|
if(Iter == Node)
|
||
|
break;
|
||
|
Prev = Iter;
|
||
|
}
|
||
|
if(Prev)
|
||
|
Prev->Next = Node->Next;
|
||
|
free(Node);
|
||
|
}
|
||
|
|
||
|
// NOTE: frees the whole list
|
||
|
void list_free(node **Head)
|
||
|
{
|
||
|
for(node *Iter = *Head; Iter; )
|
||
|
{
|
||
|
node *ToFree = Iter;
|
||
|
Iter = Iter->Next;
|
||
|
|
||
|
free(ToFree);
|
||
|
}
|
||
|
}
|
||
|
|
||
|
int main(int argc, char **argv)
|
||
|
{
|
||
|
// NOTE: beginning of the list
|
||
|
// right now the list is empty
|
||
|
node *Head = 0;
|
||
|
|
||
|
list_add(&Head, 'c');
|
||
|
list_add(&Head, 'y');
|
||
|
list_add(&Head, 'b');
|
||
|
|
||
|
node *ToBeRemoved = list_get(&Head, 'y');
|
||
|
list_remove(&Head, ToBeRemoved);
|
||
|
|
||
|
list_add(&Head, 'a');
|
||
|
node *InsertAfter = list_get(&Head, 'c');
|
||
|
list_insert_after(InsertAfter, 'd');
|
||
|
|
||
|
for(node *Iter = Head; Iter; Iter = Iter->Next)
|
||
|
{
|
||
|
printf("%c ", Iter->Character);
|
||
|
}
|
||
|
printf("\n");
|
||
|
|
||
|
list_free(&Head);
|
||
|
|
||
|
}
|