泛型链表的反转

#include<iostream>
#include "stdlib.h"
using namespace std;
template<typename T>
class mylist
{
private:
	struct node
	{
		T data;
		node* m_next;
		node()
		{
			m_next=NULL;
		}
	};
public:
	
	mylist()
	{
		m_head =NULL;
		m_isize =0;
	}
private:

	
	node* m_head;
	int m_isize;
public:
	void show()
	{
		node * ptemp= m_head;
		while(ptemp->m_next !=NULL)
		{
			std::cout<<ptemp->data<<" ";
			ptemp=ptemp->m_next;
		}
		std::cout<<ptemp->data<<std::endl;
	}
	void push_back(T val )
	{
		node* pnode = new node;
		pnode->data = val;
		m_isize++;
		if(!m_head)
		{
			m_head =pnode;
			m_head->m_next=NULL;
		}
		else
		{ 
			node* pnodetemp = m_head ;
			while(pnodetemp->m_next !=NULL)
			{
				pnodetemp= pnodetemp->m_next;
			}
			pnodetemp->m_next = pnode;
		}
	}

	bool insertNode(int index ,T val)
	{
		node * ptemp= m_head;
		if(index<=m_isize-1)
		{
			int ix=0;
			node* pnode = new node;
			pnode->data = val;
			node* poldnode=ptemp;
			while (index != ix++  && ptemp && ptemp->m_next)
			{
				poldnode=ptemp;
				ptemp = ptemp->m_next;
			}
			if(index != 0)
			{  
				poldnode->m_next =pnode;
				pnode->m_next= ptemp;
			}
			else
			{
				pnode->m_next =m_head;
				m_head = pnode;
			}
			m_isize++;
			return true;
		}
		else
			return false;
	}
	void ReversalList()
	{
		if(m_head==NULL)
			return;
		node* firistnode =m_head;
		node* p=  m_head;
		node* q=p ? p->m_next:NULL;	
		node* m=q ? q->m_next:NULL;
		while (q  && q->m_next!=NULL)
		{
			q->m_next=p;
			p=q;
			q=m;
			m=q->m_next;
		}
		if(q)
		{
	      q->m_next=p;
		  m_head =q;
		}
		firistnode->m_next=NULL;
	}
};
void main()
{
	
	mylist<int> mlist;
	int index =1;

	mlist.push_back(1);
	mlist.push_back(2);
	mlist.push_back(3);
	mlist.push_back(4);
	mlist.push_back(5);
	mlist.show();
	cout<<"****"<<endl;

	mlist.insertNode(0,6);
	mlist.show();
	cout<<"****"<<endl;

	mlist.insertNode(1,9);
	mlist.show();
	cout<<"****"<<endl;

	mlist.insertNode(6,7);
	mlist.show();
	cout<<"****"<<endl;

	mlist.ReversalList();
	mlist.show();
	cout<<"****"<<endl;

	system("pause");
}

猜你喜欢

转载自blog.csdn.net/wuan584974722/article/details/82959621