单链表反转

挺简单的经典题, 自己写的第一个版本,变量初始化是这么做的,pPrevs = pHead, pCurrent = pHead->next, 看着也觉得怪怪的。 最后review的时候, 发现这样不会把反转前第一个节点的next置空!!!!!


修正版本:

#include "stdafx.h"
#include <iostream>
using namespace std;

struct ListNode
{
	int data;
	ListNode * pNext;
};

ListNode * ListInit(int num)
{
	ListNode *pNode = NULL;
	ListNode *pHead = new ListNode;
	pHead ->data = num;
	pHead ->pNext = NULL;
	ListNode *pPrevs = pHead;
	while (num--)
	{
		pNode = new ListNode;
		pPrevs ->pNext = pNode;
		pNode ->data = num;
		pNode ->pNext = NULL;
		pPrevs = pNode;
	}
	return pHead;
}
ListNode * ReverseIteratively(ListNode * pHead)
{
	ListNode * pOverHead = NULL;
	ListNode * pPrevs = NULL;
	ListNode * pCurrent = pHead;
	ListNode * pNext = NULL;
	while (pCurrent != NULL)
	{
		pNext = pCurrent ->pNext;
		pCurrent ->pNext = pPrevs;
		pPrevs = pCurrent;
		pCurrent = pNext;
	}
	pOverHead = pPrevs;
	return pOverHead;
}

int main()
{

	ListNode *pHead  = ListInit(6);
	ListNode *pNewHead = NULL;
	ListNode *pNode = pHead;
	while (pNode)
	{
		printf("%d  ", pNode->data);
		pNode = pNode ->pNext;
	}
	printf("\n");
	pNewHead = ReverseIteratively(pHead);
	pNode = pNewHead;
	while (pNode)
	{
		printf("%d  ", pNode->data);
		pNode = pNode ->pNext;
	}
	printf("\n");
	
	
}






你可能感兴趣的:(单链表反转)