Bootstrap

利用树形结构辅助实现去重算法

本文主要通过借助树形结构来实现去重算法,旨在阐述算法构建的一种思想。

让我们一起来体验算法思想的博大精深。

纯属原创,还请各位多多指导。

#include
#include
//define struct
typedef struct Node Node;
typedef struct Node * Pnode;
struct Node{
    int val;
    Pnode next;
};

//define algo
Pnode initLinkedList();
Pnode initLinkedList(){
    Pnode head = (Pnode)malloc(sizeof(Node));
    head->val = -1;
    head->next = NULL;
    return head;
}
void addNodeAtTail(Pnode L,int val);
void addNodeAtTail(Pnode L,int val){
    Pnode p = L;
    while(p->next){
        p = p->next;
    }
    Pnode newNode = (Pnode)malloc(sizeof(Node));
    newNode->val = val;
    newNode->next = NULL;
    p->next = newNode;
}


void printfLinkedList(Pnode L);
void printfLinkedList(Pnode L){
    Pnode p = L->next;
    while(p){
        printf("%d->",p->val);
        p = p->next;
    }
    printf("NULL\n");
}


typedef struct Tnode Tnode;
typedef struct Tnode * Ptnode;
struct Tnode{
	int val;
	int count;
	Ptnode left;
	Ptnode right;
};


Ptnode initBinaryTree(Ptnode T,int val){
	if(!T){
		Ptnode t = (Ptnode)malloc(sizeof(Tnode));
		t->val = val;
		t->count = 1;
		t->left = NULL;
		t->right = NULL;
		T = t;
		return T;
	}

	if(val == T->val){
		++T->count;
		return T;
	}
		

	if(val > T->val){
		if(!T->right){
			Ptnode t = (Ptnode)malloc(sizeof(Tnode));
			t->val = val;
			t->count = 1;
			T->right = t;
		}else{
			initBinaryTree(T->right,val);
		}
	}
	return T;

}


void printBinaryTree(Ptnode T);
void printBinaryTree(Ptnode T){
	if(T){
		printf("%d->",T->val);
	}	
	if(T->right){
		printBinaryTree(T->right);
	}
}

void delRepeat(Pnode L);
void delRepeat(Pnode L){	
	Pnode p = L->next;
	Ptnode T = NULL;
	while(p){
		T = initBinaryTree(T,p->val);
		p = p->next;
	}
	printBinaryTree(T);
	printf("NULL\n");
}

void main(){
    Pnode h1 = initLinkedList();
    addNodeAtTail(h1,1);
    addNodeAtTail(h1,2);
    addNodeAtTail(h1,2);
    addNodeAtTail(h1,3);
	addNodeAtTail(h1,3);
	addNodeAtTail(h1,4);
	addNodeAtTail(h1,9);
    printf("L1 is: ");
    printfLinkedList(h1);
	delRepeat(h1);
}