链表相邻元素翻转

这个题目自己至少看了好几遍, 早上起来自己手写了一下,又在电脑上实现了一下,发现最后还是出现了问题。

问题包括:

对当前结点的pNext没有设置,导致最后俩节点出现了循环环;
while条件设置出错,只判断了cur,没有判断cur->pNext;

对一个结点的情形没有考虑到。

// reverNode.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include "windows.h"
#include "iostream"
using namespace std;

typedef struct ListNode
{
	int mVlaue;
	ListNode* pNext;
};

ListNode* reverseList(ListNode* head)
{
	if (!head || head->pNext==NULL)
		return head;
	ListNode* NewHead;
	ListNode* pre = NULL;
	ListNode* cur = head;
	ListNode* Next = NULL;
	while (cur!=NULL && cur->pNext!=NULL)
	{
		if (cur != head)
			pre->pNext = cur->pNext;
		if (cur == head)
			head = cur->pNext;
		pre = cur;
		Next = cur->pNext->pNext;
		cur->pNext->pNext = cur;
		cur->pNext = Next;
		cur = Next;
	}
	return head;
}
ListNode* creatList()
{
	ListNode* head = NULL;
	ListNode* CurNode = head;
	for (int i=1;i<=5;i++)
	{
		ListNode* TempNode = new ListNode;
		TempNode->mVlaue = i;
		TempNode->pNext = NULL;
		if (head == NULL)
		{
			CurNode = TempNode;
			head = TempNode;
		}
		else
		{
			CurNode->pNext = TempNode;
			CurNode = TempNode;
		}
	}
	return head;
}
void printList(ListNode* head)
{
	while (head)
	{
		if (head->pNext)
			cout<<head->mVlaue<<"->";
		else
			cout<<head->mVlaue;
		head= head->pNext;
	}
	cout<<endl;
}
int _tmain(int argc, _TCHAR* argv[])
{
	ListNode* head = NULL;
	head = creatList();
	printList(head);
	ListNode* NewHead = reverseList(head);
	printList(NewHead);
	system("pause");
	return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值