码迷,mamicode.com
首页 > 编程语言 > 详细

C++单链表逆序(时间与空间的考虑)

时间:2015-04-13 11:05:21      阅读:151      评论:0      收藏:0      [点我收藏+]

标签:

#include <iostream>
using namespace std;
struct Node
{
	int data;
	Node * next;
	Node(int x=0):data(x),next(NULL){}
};
class List
{
		public:
    List()
		{	
			first = new Node();
		}
		void Insert(int x)
		{	
			Node *s = new Node(x);
			s->next = first->next;
			first->next = s;
		}
		void Show()
		{	
			Node *p = first;
			while(p->next!=NULL)
			{
				cout<<p->next->data<<"  ";
				p=p->next;
			}
			cout<<endl;
		}
		void Grail()//逆序
		{
			Node *p = first;
			Node *q = first->next;
			p = NULL;
			while(q!=NULL)
			{
				Node* m =q->next;
				q->next = p;
				p = q;
				q = m ;
			}
			first->next=p;
		}
	private:
		Node *first;
};
int main()
{
	int Item;
	List list;
	while(cin>>Item,Item!=-1)
		{
		 list.Insert(Item);
		}
		list.Show();
		list.Grail();
		list.Show();
	return 0;
}

C++单链表逆序(时间与空间的考虑)

标签:

原文地址:http://blog.csdn.net/liuhuiyan_2014/article/details/45021539

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!