zoukankan      html  css  js  c++  java
  • 逆转单链表

    #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;
    }
    

      

  • 相关阅读:
    java依赖注入
    Mac OS 中的 Python(和 NumPy)开发环境设置
    英语巴菲
    经济学原理
    You are beautiful
    大数据之tachyon(未完版)
    机器学习温和指南
    机器学习之回归
    Mac 命令
    批处理--批量打开程序&批量关闭程序
  • 原文地址:https://www.cnblogs.com/lsh123/p/7569046.html
Copyright © 2011-2022 走看看