那天去阿里巴巴面试的时候,那个老师临场考我写这个算法,当时有点紧张,没写出来。只是说了下具体的步骤,回来后上机实现了下,觉得这种简单的问题实在是应该很容易的拿下。
具体代码如下:
//#include <stdio.h>
#include <iostream>
using namespace std;
typedef struct NODE{
int elem;
struct NODE* next;
}Node;
void ReverseList( Node** head ){//注意这里必须用指向指针的指针,因为头结点在不断的发生变化。否则则为值传递。
Node *t1,*t2;
t1 = *head;
t2 = t1->next;
while( t2 )//每次使t1后面的结点即t2成为头结点。做到最后指针“游走”到链表的尾结点结束算法。
{
t1->next = t2->next;
t2->next = *head;
*head = t2;
t2 = t1->next;
}
}
void print( Node* thead)//
{
for( ; thead; thead = thead->next)
cout << (thead->elem) << '/t';
cout<<endl;
}
int main()
{
int a[] = { 0, 2 };
Node *thead, *temp;
int length = sizeof(a)/sizeof(a[0]);
Node *List = ( Node* )malloc( sizeof( Node ) );
List->elem = a[ 0 ];
List->next = NULL;
thead = List;
for( int p = 1; p < length; p++ )//尾插法构建链表。
{
temp = (Node*)malloc(sizeof(Node));
temp->elem = a[ p ];
temp->next = List->next;
List->next = temp;
List = List->next;//List指向的是链表的尾结点。
}
print(thead);
ReverseList(&thead);
print(thead);
return 0;
}