寒假項目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;}
運行結果: