Winter vacation project 1-Dynamic Linked List experience (transformation) (6), winter vacation 1-
/** Copyright (c) 2014, School of Computer Science, Yantai University * All rights reserved. * file name: test. cpp * Author: Liu Chang * completion date: January 23, 2015 * version No.: v1.0 ** Problem description: modifying the linked list in the blog example. * Input Description: Enter n (n is the node data ). * Program output: output dynamic linked list
(6) Compile the void insert (int x) function to insert the node with the value of x to the ordered linked list created by make_list3.
# Include <iostream> # include <cstdio> using namespace std; struct Node {int data; // the data of the Node struct Node * next; // points to the next Node }; node * head = NULL; // define the head of the linked list as a global variable for subsequent operations void make_list3 (); // create the void out_list (); // output linked table void insert (int x); // insert the node with the value of x into the ordered linked list so that the still ordered 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 <"Enter positive numbers (end with 0 or a negative number) to create a linked list :" <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 <"the data in the linked list is:" <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 <"A new node has been inserted... "<endl; return ;}
Running result: