最近在学习算法,跟大家讨论一条题目
是微软面试一百题里面的题目,我有一个地方看不懂,希望跟大家讨论一下。
题目:用一种算法颠倒一个连接表的顺序(应该是单链表吧)。要求不要递归做。
下面是答案的代码,有点看不懂
Node * revereNonrecurisve(Node * head)
{
if (head == null)
{
return head;
}
Node * p = head;
Node * previous = null;
while (p->next != null)
{
p->next = previous;
previous = p;
p = p->next;
}
p->next = previous;
return p;
}
p->next = previous;
previous = p;
p = p->next;
previous = p;
p = p->next;
p->next = previous;
Node * revereNonrecurisve(Node * head)
{
if (head == null)
{
return head;
}
Node * p = head;
Node * previous = null;
while (head != null)
{
head = p->next;
p->next = previous;
previous = p;
p = head;
}
p->next = previous;
return p;
}
#include <iostream>
struct Node
{
int data;
Node* next;
};
void addtolist(Node*& head, int a)
{
Node* p = new Node;
p->data = a;
p->next = head;
head = p;
}
void showlist(Node* head)
{
while (head != NULL)
{
std::cout << head->data << ' ';
head = head->next;
}
std::cout << std::endl;
}
void eraselist(Node*& head)
{
while (head != NULL)
{
Node* p = head;
head = head->next;
delete p;
}
}
Node * revereNonrecurisve(Node * head)
{
Node * previous = NULL;
Node* p = NULL;
while (head != NULL)
{
p = head->next;
head->next = previous;
previous = head;
head = p;
}
return previous;
}
int main()
{
Node* head = NULL;
for (int i = 0; i < 10; i++)
addtolist(head, i + 1);
showlist(head);
head = revereNonrecurisve(head);
showlist(head);
eraselist(head);
return 0;
}
// 运行结果
// 10 9 8 7 6 5 4 3 2 1
// 1 2 3 4 5 6 7 8 9 10