Linked List

From Ta Wiki
Revision as of 00:11, 8 March 2019 by Tata (talk | contribs) (Created page with " #include<stdio.h> #include<stdlib.h> struct Node { int val; Node* next; }; Node* new_node(int val) { Node* node = (Node*)malloc(sizeof(Node)); node->val = val...")
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to navigation Jump to search
#include<stdio.h>
#include<stdlib.h>

struct Node {
	int val;
	Node* next;
};

Node* new_node(int val) {
	Node* node = (Node*)malloc(sizeof(Node));
	node->val = val;
	node->next = NULL;
	return node;
}

// ถ้าไม่เจอจะ return โหนดสุดท้าย
Node* find_parent(Node* node, int val) {
	if(node == NULL)return NULL;
	if(node->next == NULL)return node;
	if(node->next->val == val)return node;
	return find_parent(node->next, val);
}

Node* find(Node* node, int val) {
	if(node == NULL)return NULL;
	if(node->val == val)return node;
	return find(node->next, val);
}

void insert(Node* root, int val) {
	Node* node = new_node(val);
	node->next = root->next;
	root->next = node;
}

void insert_before(Node* root, int p_val, int val) {
	Node* parent = find_parent(root, p_val);
	if(parent == NULL)return;
	insert(parent, val);
}

void delete_node(Node* node, int val) {
	Node* parent = find_parent(node, val);
	if(parent == NULL)return;
	if(parent->next == NULL)return;
	Node* tmp = parent->next;
	parent->next = parent->next->next;
	free(tmp);
}

void print_recursive(Node* node) {
	if(node == NULL)return;
	printf("%d ", node->val);
	print_recursive(node->next);
}

void print_for(Node* node) {
	for( ; node != NULL; node = node->next)
	printf("%d ", node->val);
}

int main(int argc, char *argv[])
{
	Node* root = new_node(0);

	for(int i = 1; i <= 10; i++) {
		insert(root, i);
		print_recursive(root->next);
		printf("\n");
	}
	printf("\n");

	for(int i = 1; i <= 10; i += 4) {
		delete_node(root, i);
		print_for(root->next);
		printf("\n");
	}
	printf("\n");

	for(int i = 1; i <= 10; i += 3) {
		insert_before(root, i, i * 2);
		print_for(root->next);
		printf("\n");
	}
	printf("\n");

getchar();

return 0;
}