博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

程序员面试100题之十九,反转链表

Posted on 2010-09-24 16:13  KurtWang  阅读(223)  评论(0编辑  收藏  举报
#include "stdafx.h"

struct Node
{
	Node * next;
	int value;
};

Node * reverse(Node * head)
{
	if(!head)
		return NULL;
	Node * prev = NULL;
	Node * cur = NULL;
	Node * curNext = head;
	while(curNext)
	{
		cur = curNext;
		curNext = curNext->next;
		cur->next = prev;
		prev = cur;
	}
	return cur;
}

int _tmain(int argc, _TCHAR* argv[])
{
	Node * n1 = new Node();
	Node * n2 = new Node();
	Node * n3 = new Node();
	n1->value = 1;
	n1->next = n2;
	n2->value = 2;
	n2->next = n3;
	n3->next = NULL;
	n3->value = 3;

	Node * temp = reverse(n1);

	while(temp != NULL)
	{
		printf("%d ",temp->value);
		temp = temp->next;
	}
	return 0;
}