16:28:09第6题
------------------------------------
微软亚院之编程判断俩个链表是否相交给出俩个单向链表的头指针,
比如h1,h2,判断这俩个链表是否相交。
为了简化问题,我们假设俩个链表均不带环。
问题扩展:
1.如果链表可能有环列?
2.如果需要求出俩个链表相交的第一个节点列?
/*1.首先假定链表不带环
那么,我们只要判断俩个链表的尾指针是否相等。
相等,则链表相交;否则,链表不相交。
2.如果链表带环,
那判断一链表上俩指针相遇的那个节点,在不在另一条链表上。
如果在,则相交,如果不在,则不相交。
所以,事实上,这个问题就转化成了:
1.先判断带不带环
2.如果都不带环,就判断尾节点是否相等
3.如果都带环,判断一链表上俩指针相遇的那个节点,在不在另一条链表上。
如果在,则相交,如果不在,则不相交。
*/
//用两个指针,一个指针步长为1,一个指针步长为2,判断链表是否有环
bool check(const node* head)
{
if(head==NULL)
return false;
node *low=head, *fast=head->next;
while(fast!=NULL && fast->next!=NULL)
{ low=low->next; fast=fast->next->next;
if(low==fast)
return true;
}
return false;
}
第9题
-----------------------------------
判断整数序列是不是二元查找树的后序遍历结果
题目:输入一个整数数组,判断该数组是不是某二元查找树的后序遍历的结果。
如果是返回true,否则返回false。
例如输入5、7、6、9、11、10、8,由于这一整数序列是如下树的后序遍历结果:
8
/ /
6 10
/ / / /
5 7 9 11
因此返回true。
如果输入7、4、6、5,没有哪棵树的后序遍历的结果是这个序列,因此返回false。
*/
bool verifySequenceOfBST(int sequence[],int length)
{
if(sequence == NULL||length <=0)
return false;
int root= sequence[length-1];
int i=0;
for(; i<length-1;++i)
{if(sequence[i]>root)break;}
int j=i;
for(;j<length-1;++j)
{if(sequence[j]<root)return false;}
bool left=true;
if(i>0) left=verifySequenceOfBST(sequence,i);
bool right =true;
if(i<length-1) right= verifySequenceOfBST(sequence+i, length -i-1);
return (left&&right);
}
//9.word reversion
//input: I am a student
//output: student. a am I
#include <iostream>
#include <string>
using namespace std;
class ReverseWords{
public:
ReverseWords(string* wo):word(wo){}
void reverse()
{
int length= word->size();
int begin=-1,end=-1;
for(int i=0;i<length;++i)
{
if(begin==-1&&word->at(i)==' ')
continue;
if(begin==-1)
{begin=i;continue;}
if(words->at(i)==' ')
end=i-1;
else if(i==length-1)
end=i;
else continue;
reverse(begin,end); //1.字母翻转
begin=end=-1;
}
reverse(0,length-1);
}
private:
void reverse(int begin,int end)
{
while(begin<end)
{
char t= words->at(begin);
words->at(begin)= words->at(end);
words->at(end)=t;
++begin;
--end;
}
}
string* words;
}