链表在某位置插入某数

来源:互联网 发布:去外企工作好吗 知乎 编辑:程序博客网 时间:2024/06/15 06:13
struct node{    int count;    int data;    node* next;};node head;node* creat(){    head.next=0;    node* r=&head;    r->next=NULL;    node* p;    int data;    while(cin>>data&&data)//以0结束链表输入    {        p=new node;        p->count=1;        p->data=data;        p->next=r->next;        r->next=p;        r=p;    }    return &head;}void insert( const int& index, const int& data)//在index位置插入数据data{    int i=0;    node* p=&head;    while(i++<index-1)    {        p=p->next;    }    node* obj=new node;    obj->data=data;    obj->next=p->next;    p->next=obj;}void show(){    node* p=head.next;    while(p)    {        cout<<p->data;        if(p->next)            cout<<' ';        p=p->next;    }    cout<<endl;}void discard(){    node* p=head.next;    while(p)    {        node* q=p;        p=p->next;        delete q;    }}int main(){   int index;   int data;   while(cin>>index>>data&&(index!=0||data!=0))//遇到 index和data均为0的时候结束程序   {       creat();       insert(index,data);       show();       discard();   }    return 0;}

原创粉丝点击