【数据结构】构造有序的单链表

描述

构造有序(升序)的单链表
并实现单链表的逆置(可以采用结构化的程序设计方法实现,即不必定义类)

输入

输入链表中的数据。(用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();

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值