笔试题见微软2014校园招聘笔试试题
这里主要写一下最后一道题。
主要分三步:
1:通过“两步走 一步走”的方法,找到中间点或者前半列的最后一个点(偶数个数时)
2:“1”中的点之后的所有点顺次入栈。
3:只要栈不为空,依次出栈然后按题目要求改点指针。
点结构为:
struct Node
{
int val_;
Node* next;
Node(int x) :val_(x), next(NULL){}
};
构建链表
Node * ConstructList(int *p, int len)
{
if (p == NULL || len <= 0) return NULL;
int i = 0;
Node *head = NULL;
Node *tmp = NULL;
while (i < len)
{
Node * pNode = new Node(*(p + i));
if (tmp)
{
tmp->next = pNode;
tmp = pNode;
tmp->next = NULL;
}
else
{
head = pNode;
tmp = pNode;
tmp->next = NULL;
}
++i;
}
return head;
}
下面是翻转链表函数
void ReverseList(Node *head)
{
if (head == NULL || head->next == NULL || head->next->next == NULL) return;
Node * step1 = head , *step2 = head;
while (step1->next)
{
step1 = step1->next;
if (step1->next)
{
step1 = step1->next;
step2 = step2->next;
}
}
//step1 is the last,step2 is the len/2-1. (from 0)
Node *ts = step2->next;
step2->next = NULL;
vector<Node * > vc;
while (ts)
{
vc.push_back(ts);
ts = ts->next;
}
step1 = head;
while (vc.size() >= 0)
{
if (vc.size() == 0)
break;
step2 = step1->next;
step1->next = vc[vc.size() - 1];
vc.pop_back();
step1->next->next = step2;
step1 = step2;
}
}