链表逆序

     那天去阿里巴巴面试的时候,那个老师临场考我写这个算法,当时有点紧张,没写出来。只是说了下具体的步骤,回来后上机实现了下,觉得这种简单的问题实在是应该很容易的拿下。

 

具体代码如下:

 

//#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;

}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值