废话不多说,直接上代码。
1 #include <iostream> 2 #include <cstdlib> 3 4 using namespace std; 5 6 typedef int ElemType; 7 8 struct Node 9 { 10 ElemType data; 11 Node* next; 12 }; 13 14 typedef Node* LinkList; 15 16 void input(ElemType* a) 17 { 18 cout<<"please enter the date value of the current node: "; 19 cin >> *a; 20 } 21 22 //尾插法,我觉得更加符合我的习惯。 23 void CreateLinkList(LinkList* L,int n,void input(ElemType*)) 24 { 25 cout<<"this is the tail-insert-proach..."<<endl; 26 LinkList s; 27 *L = new Node; 28 LinkList p = *L; 29 (*L)->next = NULL; 30 for(;n>0;n--) 31 { 32 s = new Node; 33 input(&s->data); 34 s->next = NULL; 35 p->next = s; 36 p = s; 37 } 38 s->next = NULL; 39 } 40 41 void DestoryList(LinkList *L) 42 { 43 cout<<"we are going to delete the linklist..."<<endl; 44 LinkList q,p = *L; 45 while(p != NULL) 46 { 47 q = p->next; 48 delete p; 49 p = q; 50 } 51 52 *L = NULL; 53 cout<<"we have destoryed the linklist..."<<endl; 54 } 55 56 int main() 57 { 58 LinkList L; //头指针,指向创建的头结点。头结点的data为空,尾结点的next为NULL 59 int n; 60 cout<<"please enter the number of needed nodes(except the head node)..."<<endl; 61 cin>>n; 62 CreateLinkList(&L,n,input); 63 DestoryList(&L); 64 return 0; 65 }