Signly and Doubly Linked List

Signly Linked List

Signly linked list is a single direction linked list. A list contains multiple nodes and each node stores the pointer of next node. You may need to hold the head node to begin traversal, and run until reaching NULL pointer.

When to use linked list ?

Compared to array, linked list can grow or shrink in size dynamically, which makes them more flexible when the amount of data is unknown or change over time.

Define a node

typedef struct Node_t {
	int value;
	struct Node_t *node;
} Node;

Create a list

int a[] = {1,2,3,4,5};
Node *head = NULL;
Node *curr = NULL;
head = (Node *) malloc(sizeof(Node));
curr = head;
curr->value = a[0];
for (int i = 1; i < sizeof(a) / sizeof(int); i++) {
	Node *node = (Node *) malloc(sizeof(Node));
	node->value = a[i];
	node->next = NULL;
	curr->next = node;
	curr = curr->next;
}

Traverse a list

void traverse(Node *head) {
	Node *curr = head;
	while (curr != NULL) {
		printf("Node value is %d", curr->value);
		curr = curr->next;
	}
}

Search specific node

void search(Node *head) {
	Node *node = head;
	while (node != NULL) {
		if (node->value == EXPECTED) {
			return;
		}
		node = node->next;
	}
}

Insert a node

void inseration (Node *head, int value) {
	Node *node = head;
	while (node->next != NULL) {
		node = node->next;
	}
	node->next = (Node *)malloc(sizeof(Node));
	node->next->next = NULL;
	node->next->value = value;
}

Doubly Linked List

A doubly linked list is a two direction linked list. A list contains multiple nodes, and each node stores the data, the pointer of the next node, and the pointer of the previous node. You may need to hold the head node to begin forward traversal or the tail node to begin backward traversal and run until reaching a NULL pointer.