程序员面试100题(算法)之反转单链表(含单向链表的创建和打印)

// 程序员面试100题(算法)之反转单链表
#include "stdafx.h"
#include <iostream>

using namespace std;

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

LinkNode *CreateLink(LinkNode *headNode, int &length)
{
	int data = 0;
	LinkNode *previous, *post;

	if(NULL == headNode)
	{
		cin >> data;
		if(-1 == data)
			return NULL;
		headNode = (LinkNode*)malloc(sizeof(LinkNode));
		if(headNode)
		{
			headNode->value = data;
			headNode->next = NULL;
			length++;
		}
		else
		{
			cout << "No space" <<endl;
		}
	}

	previous = post = headNode;
	cin >> data;
	while(data != -1)
	{
		post = (LinkNode*)malloc(sizeof(LinkNode));
		if(post)
		{
			post->value = data;
			post->next = NULL;
			previous->next = post;
			previous = post;
			length++;
		}
		else
		{
			cout << "No space" << endl;
		}

		cin >> data;
	}

	return headNode;
}

void PrintLink(LinkNode *headNode)
{
	if(headNode == NULL)
	{
		cout << "Linklist is empty" <<endl;
		return;
	}

	LinkNode *p = headNode;
	
	while(p)
	{
		cout << p->value << "  ";
		p = p->next;
	}

	cout << endl;
}

LinkNode *ReverseLink(LinkNode *headNode)
{
	if(NULL == headNode)
		return NULL;

	if(NULL == headNode->next)
		return headNode;

	LinkNode *previous, *post, *r;
	previous = headNode;
	post = headNode->next;

	while(post != NULL)
	{
		r = post->next;
		post->next = previous;
		previous = post;
		post = r;
	}

	headNode->next = NULL;

	return previous;
}

int _tmain(int argc, _TCHAR* argv[])
{
	int length = 0;
	LinkNode *headNode = NULL;

	cout << "Create a linklist(end up with -1)" <<endl;
	headNode = CreateLink(headNode, length);
	PrintLink(headNode);

	headNode = ReverseLink(headNode);
	PrintLink(headNode);

	return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值