刘收获

导航

逆转单链表

#include<iostream>
using namespace std;

template<class T>
struct ListNode
{
	T Data;
	ListNode* Flink;
	ListNode() { Flink = NULL; }
	ListNode(T SHData, ListNode<T>* SHFlink = NULL)
	{
		Data = SHData;
		Flink = SHFlink;
	}
};

template<class T>
class SHClass
{
public:
	ListNode<T>* Head;
	SHClass();
	void SHAddNode(T SHData);
	ListNode<T>* ReverseList(ListNode<T>* Head);
};

template<class T>
SHClass<T>::SHClass()
{
	this->Head = NULL;
}

template<class T>
void SHClass<T>::SHAddNode(T data)         
{
	ListNode<T> *NewNode = NULL;
	if (Head == NULL)
	{
		NewNode = new ListNode<T>(data, Head);
		Head = NewNode;
	}
	else
	{
		ListNode<T> *lptr = Head;

		while (lptr->Flink != NULL)
		{
			lptr = lptr->Flink;
		}
		NewNode = new ListNode<T>(data, lptr->Flink);
		lptr->Flink = NewNode;
	}
}

template<class T>                              
ListNode<T>* SHClass<T>::ReverseList(ListNode<T>* head)
{
	ListNode<T>* p = NULL; //Blink   Node
	ListNode<T>* r = head; //Current Node
	ListNode<T>* q = NULL; //Flink   Node
	while (r != NULL)
	{
		q = r->Flink;  //The Flink Node
		r->Flink = p;  //Reverse!
		p = r;         //For Next Cycle
		r = q;		   //For Next Cycle
	}
	return p;
}


int main()
{
	SHClass<int> a;
	a.SHAddNode(1);
	a.SHAddNode(2);
	a.SHAddNode(3);
	ListNode<int> *lptr;
	lptr = a.Head;
	while (lptr != NULL)
	{
		cout << lptr->Data;
		lptr = lptr->Flink;
	}
	cout << endl;
	a.Head = a.ReverseList(a.Head);
	lptr = a.Head;
	while (lptr != NULL)
	{
		cout << lptr->Data;
		lptr = lptr->Flink;
	}
	return 0;
}

  

posted on 2017-09-21 15:59  沉疴  阅读(136)  评论(0编辑  收藏  举报