无头结点的链表逆置

要是有头结点的话,代码可以简单很多啊!  这是无头结点的链表逆置,链表的生成不想用函数生成了,直接强制生成了一个。

// delete.cpp : 定义控制台应用程序的入口点。
#include "stdafx.h"
#include <iostream>
using namespace std;

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


ListNode *ReverseList( ListNode *pHead )
{
	ListNode *pPre = NULL;  //始终保存前面断掉的链表的头指针
	ListNode *pCur = pHead;   //当前处理的节点
	ListNode *pReserve = NULL;  //保存当前节点的下一个节点,防止断掉了

	while ( pCur != NULL)
	{
		pReserve = pCur -> next;
		pCur ->next = pPre;
		pPre = pCur;
		pCur = pReserve;

	}

	return pPre;
}

int main()
{
	ListNode a1;  
	ListNode *head = &a1;  
	a1.data = 2;  

	ListNode a2;  
	a1.next = &a2;  
	a2.data = 3;  

	ListNode a3;  
	a2.next = &a3;  
	a3.data = 1;  

	ListNode a4;  
	a3.next = &a4;  
	a4.data = 4;  
	a4.next = NULL; 

	ListNode *result = ReverseList( head );

	for( ListNode *pBeg = result ; pBeg != NULL; pBeg = pBeg->next)  
	{  
		cout<<pBeg->data<<endl;  
	}  
    
}


你可能感兴趣的:(链表,逆置,无头节点)