面试题-单链表的逆序

来源:互联网 发布:龙腾世纪审判优化补丁 编辑:程序博客网 时间:2024/04/29 16:37
#include <stdlib.h>#include <stdio.h>#include <iostream>#include <time.h>#define _random(x) (random()%x)using namespace std;struct LinkNode {int data;LinkNode* next;};LinkNode* ReverseLink(LinkNode* head){LinkNode *prev=NULL, *next=NULL;while(head){next = head->next;head->next = prev;prev = head;head = next;}return prev;}int main(){LinkNode* first = NULL;LinkNode* cur = NULL;srandom((int)time(0));for(int i=0; i<10; ++i){LinkNode* pa = new LinkNode;pa->data = _random(100);if(cur) {cur->next = pa;}else {first = pa;}cur = pa;}cur->next = NULL;cur = first;while(cur) {cout<<cur->data<<"  ";cur = cur->next;}cout<<endl;LinkNode* header = ReverseLink(first);while(header) {cout<<header->data<<"  ";header = header->next;}cout<<endl;return 0;}


输出结果:



这里没有采用递归的写法,感觉递归的写法, 不太好理解, 且实战性稍差.

简单的流程介绍:




原理可以参考:  http://blog.csdn.net/autumn20080101/article/details/7607148 

分析的很透彻.

0 0