Skip to content

Instantly share code, notes, and snippets.

@mitnk
Created November 21, 2012 12:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mitnk/4124702 to your computer and use it in GitHub Desktop.
Save mitnk/4124702 to your computer and use it in GitHub Desktop.
A simple linked list
#include <stdio.h>
#include <stdlib.h>
typedef struct Node {
int data;
struct Node *next;
} Node;
Node *create_node(int n)
{
Node *current = (Node *)malloc(sizeof(Node));
current->data = n;
current->next = NULL;
return current;
}
typedef struct {
Node *head;
Node *rear;
} LIST;
LIST init_list()
{
LIST list;
list.head = NULL;
list.rear = NULL;
return list;
}
void print_list(LIST *list)
{
if (!list->head)
printf("(empty).\n");
Node *current = list->head;
while(current)
{
if (current->next)
printf("%d -> ", current->data);
else
printf("%d\n", current->data);
current = current->next;
}
}
void append_list(LIST *list, int n)
{
Node *node = create_node(n);
Node *current = list->head;
if (!current)
{
list->head = node;
list->rear = node;
return;
}
else
{
list->rear->next = node;
list->rear = node;
}
}
int delete_element(LIST *list, int n)
{
Node *current = list->head;
if (!current)
return 0;
if (current->data == n)
{
list->head = current->next;
free(current);
return 1;
}
while(current->next)
{
if (current->next->data == n)
{
Node *node = current->next;
current->next = current->next->next;
free(node);
if (current->next == NULL)
list->rear = current;
return 1;
}
current = current->next;
}
return 0;
}
int main()
{
LIST list = init_list();
print_list(&list);
int i;
for (i = 1; i <= 1000000; ++i)
{
append_list(&list, i);
}
printf("generated.\n");
getchar();
printf("deleting ...\n");
for (i = 1; i <= 1000000; i += 2)
{
delete_element(&list, i);
if (i % 100000 == 1)
printf("%d...\n", i);
}
printf("Done\n");
getchar();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment