描述
构造有序(升序)的单链表
并实现单链表的逆置(可以采用结构化的程序设计方法实现,即不必定义类)
输入
输入链表中的数据。(用0表示输入的结束,0不能添加到链表中)
输出
按顺序输出有序链表中的数据
#include <iostream>
using namespace std;
template <class t>
struct node
{
t data;
node <t> *next;
};
template <class t>
class List
{
public:
List();
void create(t a[],int n);
void print();
void Insert(t x);
void Reverse() ;
node <t> *first;
};
template <class t>
List<t>::List()
{
first =new node<t>;
first->next=NULL;
}
template <class t>
void List<t>::Insert(t x)
{
node<t> *s,*p,*front;
s=new node<t>;
s->data=x;
front=first;
p=first->next;
while(p && x>p->data)
{
front=p;
p=p->next;
}
s->next=p;
front->next=s;
return ;
}
template <class t>
void List<t>::create(t a[],int n)
{
for(int i=0; i<n; i++)
Insert(a[i]);
}
template <class t>
void List<t> ::print ()
{
node <t> *p;
p=first->next;
while (p!=NULL)
{
cout<<p->data<<" ";
p=p->next;
}
}
template <class t>
void List<t>:: Reverse()
{
node<t> *p=first->next,*q;
first->next=NULL;
while (p!=NULL)
{
q=p->next;
p->next = first->next;
first->next = p;
p=q;
}
}
int main()
{
int t;
int a[100];
int i=0;
while (cin>>t&&t)
{
a[i]=t;
i++;
}
List<int> ob;
ob.create(a,i);
ob.print();
cout<<endl;
ob.Reverse();
ob.print();
}