这里附上我的华为2008校园招聘北京笔试最后编程题答案:
第一题:猫吃老鼠,就是猴子选大王的改版,循环链表解决:
#include <iostream>
using namespace std;
struct node
{
int date;
struct node* next;
};
typedef struct node Node;
int main(int argc, char* argv[])
{
int count,begin,i;
do{
cout<<"请输入总数和起始位置:"<<endl;
cin>>count>>begin;
}while(count<=0 || begin<=0 || begin>count);
i = count;
Node *head = new Node,*last,*pre;
head->date = count;
head->next = NULL;
last = head;
if(begin+1 == count) pre = head;
while (--i != 0)
{
Node* temp = new Node;
temp->date = i;
temp->next = NULL;
if(i == begin+1) pre = temp;
last->next = temp;
last = temp;
}
last->next = head;
if(begin == count) pre = last;
i = count - 1;
while (--i != 0)
{
Node* temp = pre->next;
pre->next = pre->next->next;
delete temp;
pre = pre->next;
}
cout<<pre->date<<endl;
return 0;
}
第二题:求未知链表的中间位置算法:
struct node* findmid(struct node* head)
{
struct node *one = head,*two = head;
while(two != NULL)
{
two = two->next;
if(two != NULL)
{
two = two->next;
one = one->next;
}
}
return one;
}