天天看點

算法導論-連結清單

編譯環境:dev-c++

以C89的标準來寫的,自測通過,後續會陸續更新

#include <stdio.h>
#include <stdlib.h>

typedef struct _node
{
	int value;
	struct _node *next;
} Node;


void ll_insert(Node **root,int value){
	Node *a;
	Node *t = (Node *) malloc(sizeof(Node));
	t->value = value;
	t->next = NULL;
	printf("insert %d.\n",value);
	if(*root == NULL){		
		*root = t;
		return;
	}
	a = *root;
	while(1){
		if(a->next == NULL){
			a->next = t;
			break;
		}
		a = a->next;
	}
}

/* 反轉單連結清單 */
void ll_reversal(Node **head_ref){
	Node* prev   = NULL;
    Node* current = *head_ref;
    Node* next;
    while (current != NULL)
    {
        next  = current->next;  
        current->next = prev;   
        prev = current;
        current = next;
    }
    *head_ref = prev;
}


void ll_printf(Node *root){
	Node *t;
	if(root == NULL){
		printf("root null/n");
		return;
	}
	t = root;
	while(1){
		printf("value : %d\n", t->value);
		if(t->next != NULL){
			t = t->next;
		} else {
			break;
		}
	}
}

int main(){

	int i = 0;
	Node *root = NULL;

	//先插入10個元素
	for (i = 0; i < 10; ++i)
	{
		ll_insert(&root,i);		
	}

	//列印
	ll_printf(root);

	//搜尋
	ll_search(root,2);

	//删除3個元素
	ll_delete(&root,2);

	//列印
	ll_printf(root);

	printf("ll_reversal linkedlist\n");
	//反轉
	ll_reversal(&root);
	//列印
	ll_printf(root);


	return 0;
}
           

繼續閱讀