单链表反转

#include <iostream>
#include <string>

using namespace std;

template<typename Object>
class linkList
{
private:
	struct Node
	{
		Object data;
		Node *next;

		Node(const Object &d=Object{ },Node *n=nullptr)
		:data(d),next(n)
		{ }
	};


public:

	linkList()
	{
		init();
	}

	void listInsert(const Object x)
	{
		Node *ptr=new Node(x,nullptr);
		ptr->next=head->next;
		head->next=ptr;
		theSize++;
	}

	void print()
	{
		Node *ptr=head->next;
		while(ptr!=nullptr)
		{
			cout<<ptr->data<<" ";
			ptr=ptr->next;
		}
		cout<<endl;
	}


	void listReverse()
	{
		Node *current;
		Node *p;

		current=head->next;
		while(current->next!=nullptr)
		{
			p=current->next;   
			current->next=p->next;
			p->next=head->next;
			head->next=p;
		}
	}

private:
	Node *head;
	int theSize;
	void init()
	{
		head=new Node;
		theSize=0;
	}
};

int main()
{
	linkList<string> mylist;
	mylist.listInsert("world");
	mylist.listInsert("Hello");
	mylist.print();

	mylist.listReverse();
	mylist.print();
}

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