1、找到链表中的倒数第k个元素:
源代码如下:
struct binNode{
binNode* next;
int val;
binNode():next(NULL),val(0){};
};
binNode* createBinNode()
{
int a=0;
binNode *head=NULL,*cur=NULL;
bool mark=false;
while(cin>>a&&a!=-1)
{
if(!mark)
{
head=new binNode();
cur=head;
cur->val=a;
mark=true;
}
else
{
cur->next=new binNode();
cur->next->val=a;
cur=cur->next;
}
}
return head;
}
binNode* Reversek(int k,const binNode* head)
{
if(head==NULL)
return NULL;
const binNode* first=head,*second=head;
for(int i=0;i<k-1;i++)
{
if(first!=NULL)
first=first->next;
else
return NULL;
}
while(first!=NULL)
{
first=first->next;
second=second->next;
}
}
int main()
{
binNode* head=createBinNode();
binNode* k=Reversek(2,head);
if(NULL!=k)
cout<<k->val<<endl;
}
广度优先搜索算法,以及当前最大宽度计算方式:
struct binNode
{
int val;
binNode* left;
binNode* right;
binNode(int x=0):val(x),left(NULL),right(NULL){};
};
binNode* hehe;
binNode* createBinNode()
{
binNode* head=NULL,*cur=NULL;
int a;
bool left=false;
cur=new binNode(0);
while(cin>>a&&a!=-1)
{
if(head==NULL)
{
cur->val=a;
head=cur;
continue;
}
if(a==90)
{
hehe=cur;
}
if(left)
{
cur->left=new binNode();
cur->left->val=a;
cur=cur->left;
left=false;
}
else
{
cur->right=new binNode();
cur->right->val=a;
cur=cur->right;
left=true;
}
}
return head;
}
int GetNodeDepth(binNode* root,binNode* k)
{
if(k==NULL||root==NULL)
{
return 0;
}
else
{
if(k==root)
return 1;
else
{
int dl=GetNodeDepth(root->left,k);
int dr=GetNodeDepth(root->right,k);
return dl>dr?dl+1:dr+1;
}
}
}
bool IsSameLevel(deque<binNode*>* que,binNode* const head)
{
if(NULL==que)
return false;
deque<binNode*>::iterator itr=que->begin();
int dep=GetNodeDepth(head,*itr);
itr++;
if(itr!=que->end())
{
for(;itr!=que->end();itr++)
{
if(dep!=GetNodeDepth(head,*itr))
return false;
}
}
return true;
}
void BSF( binNode* const head)
{
if(head==NULL)
{
return ;
}
binNode* sh=head;
deque<binNode*> d_node_list;
d_node_list.push_back(sh);
int max=0;
cout<<"按照广度优先是这样的:\n";
while(!d_node_list.empty())
{
//开始检测当前队列中的元素是不是均为统一深度,由此可以找到同一深度的队列,计算队列中元素个数,得到最大宽度
if(IsSameLevel(&d_node_list,head))
{
if(max<d_node_list.size())
max=d_node_list.size();
}
binNode* top=d_node_list.front();
cout<<top->val<<endl;
d_node_list.pop_front();
if(top->right)
{
d_node_list.push_back(top->right);
}
if(top->left)
{
d_node_list.push_back(top->left);
}
}
cout<<"最大宽度是:"<<max<<endl;
}