微軟系列面試題c/c++第一題雙向鏈表

先寫的別的,近來學習算法和數據結構,有許多不懂的地方,藉助代碼提高一下自己的能力。在此,做個計劃,每兩天寫一篇博客,解決一道微軟面試題。打算一年之內完成系列博客的更新。也請大家多多探討。也算是對自己的一個貴在堅持的鍛鍊。

第一道題是把二元查找樹轉變成排序的雙向鏈表。

在數據結構中,二元查找樹是樹的左子樹比根節點小,右子樹比根節點大。每一顆子樹也是二元查找樹。二元查找樹的中序遍歷是升序的。

/*

  Problem_1.cpp
  author:B11040805
*/

#include<stdio.h>
struct BSTreeNode{
	int value;
	struct BSTreeNode *pLeft,*pRight;
	BSTreeNode(){
	pLeft=pRight=NULL;
	}
};
BSTreeNode *head=NULL,*tail=NULL;

void createList(BSTreeNode *cur){
	cur->pLeft=tail;
	if(tail!=NULL){
		tail->pRight=cur;
	}else{
		head=cur;
	}
	tail=cur;
}



BSTreeNode* visit(BSTreeNode *root)
{
	if(root!=NULL){
		visit(root->pLeft);
		createList(root);
		visit(root->pRight);
	}
	return root;
}

void addNode(BSTreeNode **root,int value){
	BSTreeNode *p;
	if(NULL!=*root)
	{
		if(value>(*root)->value){
			addNode(&((*root)->pRight),value);
		}else if(value<(*root)->value){
			addNode(&((*root)->pLeft),value);
		}else{
			printf("error");
		}
	}else{
		p=new BSTreeNode();
		p->value=value;
		*root=p;
	}
}

int main(){
	BSTreeNode *root=NULL;
	int data[]={10,6,14,4,8,12,16};
	for(int i=0;i<7;i++)
	{
		addNode(&root,data[i]);
	}
	visit(root);
	while(tail!=NULL){
		printf("%d  ",tail->value);
		tail=tail->pLeft;
	}
	printf("\n");
	while(head!=NULL){
		printf("%d  ",head->value);
		head=head->pRight;
	}
	return 0;
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章