back to home page - back to programming index
AC_C Site -C Programming - Basic Linked List

Example of Linked List in C
Linked List
The linked lists is a simple non contigues data structure, the list are consist from nodes
Code for Node
  
 struct Node
 {
 	int m_data;
 	struct Node* m_link;
 }
  
Example of Insert Function
we used double pointer to access head as local variable.
Complete Program
   
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>

struct Node
{
	int  m_data;
	struct  Node* m_link;
};

void InsertFront(struct Node** head, int  data)
{
	struct Node* newNode = ( struct  Node*)malloc(sizeof( struct  Node));
	newNode->m_data = data;
	newNode->m_link = *head;
	*head = newNode;
}

void PrintAllForward(struct  Node* head)
{
	while(NULL != head)
	{
		printf("%i ", head->m_data);
		head = head->m_link;
	}
	putchar('\n');
}

void PrintAllBackwardRec(struct  Node* head)
{
	if(NULL == head)
		return;
	PrintAllBackwardRec(head->m_link);
	printf("%i ", head->m_data);
}

void PrintAllBackward(struct  Node* head)
{
	PrintAllBackwardRec(head);
	putchar('\n');
}


void DeleteByPostion(struct  Node** head, size_t pos)
{
	struct  Node* current = *head;
	if(0 == pos)
	{
		*head = current->m_link;
		free(current);
		return;
	}
	struct  Node* last = *head;
	current = current->m_link;
	int  i;
	for(i = 1; i < pos; ++i)
	{
		last = last->m_link;
		current = current->m_link;
	}
	last->m_link = current->m_link;
	free(current); /* Learn if clear will happen */
}

void Reverse(struct  Node** head)
{
	struct  Node* current = *head;
	struct  Node* last = NULL;
	struct  Node* next;
	while(current != NULL)
	{
		next = current->m_link;
		current->m_link = last;
		last = current;
		current = next;
	}
	*head = last;
}

bool DetectIfCircular(struct  Node* head)
{
	struct  Node* slow = head;
	struct  Node* fast = head;
	while(true)
	{
		if(slow == NULL || fast == NULL)
			return  false;
		slow = slow->m_link;
		fast = fast->m_link;
		if(fast == NULL)
			return  false;
		else
			fast = fast->m_link;

		if(fast == slow)
			return  true;
	}
}

int main()
{
	struct  Node* pHead = NULL;
	InsertFront(&pHead, 1);
	InsertFront(&pHead, 4);
	InsertFront(&pHead, 7);
	InsertFront(&pHead, 9);
	InsertFront(&pHead, 10);
	InsertFront(&pHead, 12);
	PrintAllForward(pHead);
	Reverse(&pHead);
	PrintAllForward(pHead);
	Reverse(&pHead);
	PrintAllForward(pHead);
	PrintAllForward(pHead);
	PrintAllBackward(pHead);
	PrintAllForward(pHead);
	DeleteByPostion(&pHead, 1);
	PrintAllForward(pHead);
	if(DetectIfCircular(pHead))
		printf("List is Circular!\n");
	else
		printf("List is NOT Circular!\n");
	pHead->m_link->m_link->m_link->m_link->m_link = pHead->m_link->m_link;
	if(DetectIfCircular(pHead))
		printf("List is Circular!\n");
	else
		printf("List is NOT Circular!\n");
	return  0;
}