您的位置:首页 > 职场人生

面试题-单链表的逆序

2015-11-30 23:33 483 查看
#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

分析的很透彻.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: