用头插法实现单链表整表创建

 1 #include<iostream>
 2 #include<cstring>
 3 #include<stdio.h>
 4 #include<stdlib.h>
 5 using namespace std;
 6 typedef struct node{
 7     int id;
 8     node *next;
 9     node();
10     node(int);
11 }node;
12 node::node(){
13     id = 0;
14     next = NULL;
15 }
16 node::node(int i){
17     id = i;
18     next = NULL;
19 }
20 node *head;
21 void createList(int n){
22     if(n<0) return;
23     head=new node(1);
24     node *temp;
25     for(int i=2;i<=n;i++){
26         temp=new node(i);
27         temp->next=head->next;
28         head->next=temp;
29     }
30 }
31 void createList_2(int n){//顺序建表 
32     if(n<0) return;
33     head=new node(1);
34     node *temp,*p=head;
35     for(int i=2;i<=n;i++){
36         temp=new node(i);
37         p->next=temp;
38         p=temp;
39     } 
40 }
41      
42 void print(){
43     node *p=head;
44     while(p){
45         cout<<p->id<<" ";
46         p=p->next;
47     }cout<<endl;
48 }
49 int main(){
50     int n;
51     while(cin>>n){
52         createList_2(n);
53         print();
54     }
55     return 0;
56 }
View Code
原文地址:https://www.cnblogs.com/fu11211129/p/4189961.html