首页 > 编程语言 > 详细

C++单链表(下标n到下标m的逆序)

时间:2015-04-24 12:41:12      阅读:308      评论:0      收藏:0      [点我收藏+]
#include <iostream>
using namespace std;

template<typename T>
struct Node
{
	T data;
	Node *next;
	Node():next(NULL){}
};

template<typename T>
class List
{
	public:
	List()
	{
		head = new Node<T>();
	}
	void Insert(T x)
	{
		Node<T> *s = new Node<T>();
		s->data = x;
		s->next = head->next;
		head->next = s;
	}
	void Sort(int x,int y)
	{
		Node<T> *p = head;
		Node<T> *q = head;
		Node<T> *m=p;
		Node<T> *z=p->next;
		y++;
		while(x>=0)
		{	
			m=p;
			z=m->next;
			p=p->next;
			x--;
		}
		while(y>=0)
		{
			q=q->next;
			y--;
		}
		Node<T> *n = p->next;
		while(n!=q)
		{
			Node<T> *k = n->next;
			n->next=p;
			p=n;
			n=k;	
		}
                m->next=p;
		z->next=q;//注意保存指针,明确指向。
	}
	void Show()
	{
		Node<T> *p = head->next;
		while(p!=NULL)
		{	
			cout<<p->data<<" ";
			p=p->next;
		}
		cout<<endl;
	}
	private:
	Node<T> *head;
};
int main()
{
	List<int> list;
	for(int i=0;i<10;i++)
	{	
		list.Insert(i);
	}
	list.Sort(3,6);
	list.Show();
	return 0;
}

C++单链表(下标n到下标m的逆序)

原文:http://blog.csdn.net/liuhuiyan_2014/article/details/45243205

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!