寒假項目1-動態鏈表體驗(改造)(6),寒假1-

來源:互聯網
上載者:User

寒假項目1-動態鏈表體驗(改造)(6),寒假1-

/* * Copyright (c) 2014, 煙台大學電腦學院 * All rights reserved. * 檔案名稱:test.cpp * 作    者:劉暢 * 完成日期:2015 年 1  月  23  日 * 版 本 號:v1.0 * * 問題描述:改造博文樣本中的鏈表。  * 輸入描述:輸入n(n為結點資料)。* 程式輸出:輸出動態鏈表

(6)編寫函數void insert(int x),將值為x的結點插入到由make_list3建立起來的有序鏈表中。

#include <iostream>#include <cstdio>using namespace std;struct Node{    int data;                   //結點的資料    struct Node *next;          //指向下一個結點};Node *head=NULL;                //將鏈表頭定義為全域變數,以便後續操作void make_list3();              //建立鏈表void out_list();                //輸出鏈表void insert(int x);             //將值為x的結點插入到有序鏈表中,使仍有序int main(){    int x;    cin>>x;    make_list3();    out_list();    insert(x);    out_list();    return 0;}void make_list3(){    int n;    Node *p,*q,*t;    cout<<"輸入若干正數(以0或一個負數結束)建立鏈表:"<<endl;    cin>>n;    while(n>0)    {        t=new Node;        t->data=n;        t->next=NULL;        if(head==NULL)            head=t;        else        {            if (n<=head->data)            {                t->next=head;                head=t;            }            else            {                p=head;                q=p->next;                while (q!=NULL&&n>q->data)                {                    p=q;                    q=p->next;                }                if (q==NULL)                {                    p->next=t;                }                else                {                    t->next=q;                    p->next=t;                }            }        }        cin>>n;    }    return;}void out_list(){    Node *p=head;    cout<<"鏈表中的資料為:"<<endl;    while (p!=NULL)    {        cout<<p->data<<" ";        p=p->next;    }    cout<<endl;    return;}void insert(int x){    Node *q,*p,*t;    t=new Node;    t->data=x;    t->next=NULL;    if (head==NULL)        head==t;    else    {        if(x<=head->data)        {            t->next=head;            head=t;        }        else        {            p=head;            q=p->next;            while(q!=NULL&&x>q->data)            {                p=q;                q=p->next;            }            if(q==NULL)            {                p->next = t;            }            else            {                t->next=q;                p->next=t;            }        }    }    cout<<"已插入新結點..."<<endl;    return;}

運行結果:


聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.