#include<iostream>#include<malloc.h>#include<stdlib.h>usingnamespace std;typedefint ElemType;typedefstruct Node
{
ElemType data;
Node* next;}node,*pNode;
pNode create_list();voidtraverse(pNode);boolremove(pNode,int,int*);boolinsert(pNode,int,int);boolisempty(pNode head);intlenthlist(pNode head);voidsortlist(pNode head);intmain(){
pNode pHead;
pHead=create_list();//为方便测试,数据元素初始为1 3 5 7。if(isempty(pHead))cout<<"The list is empty."<<endl;else cout<<"The list is not empty."<<endl;
cout<<"The lenth of list is "<<lenthlist(pHead)<<"."<<endl;traverse(pHead);int val;if(!remove(pHead,3,&val))exit(-1);//为方便测试,删除数据元素3,即剩下的元素为1 5 7else cout<<"Your delete the num of the list, it is "<<val<<endl;traverse(pHead);if(!insert(pHead,3,2))exit(-1);//为方便测试,在第三个位置添加元素2,即当前链表的元素为1 5 2 7else cout<<"Your add one num to the list, its position is 3, the value is 2."<<endl;traverse(pHead);sortlist(pHead);
cout<<"After sorting, the list is"<<endl;//为方便测试,对链表进行排序,排序完链表元素为1 2 5 7traverse(pHead);return0;}
pNode create_list(){
pNode head=(node*)malloc(sizeof(node));//生成一个头指针,并使这个头指针指向头结点if(head==0)exit(-1);int len;pNode tail=head;//生成一个尾指针,初始化值为head
tail->next=NULL;
cout<<"Please enter lenth of list"<<endl;
cin>>len;
cout<<"Your want to create the list, its lenth is "<<len<<endl;if(len<0)exit(-1);for(int i=0;i<len;i++){
pNode New=(pNode)malloc(sizeof(node));if(New==0)exit(-1);
cin>>New->data;
tail->next=New;
New->next=NULL;
tail=New;}return head;}voidtraverse(pNode head){if(head->next==0)exit(-1);
pNode p=head->next;int i=1;while(p){
cout<<"The number "<<i<<" of the list is "<<p->data<<endl;
i++;
p=p->next;}
cout<<endl<<endl;}boolremove(pNode head,int pos,int* val){
pNode p=head;int i=0;
pNode q=NULL;while(p->next!=0&&i<pos-1){
p=p->next;i++;}if(p->next==0||i>pos-1)returnfalse;
q=p->next;*val=q->data;
p->next=q->next;
free (q);returntrue;}boolinsert(pNode head,int pos,int val){
pNode p=head;int i=0;while(p!=0&&i<pos-1){
p=p->next;
i++;}if(p==0||i>pos-1)returnfalse;
pNode q=(pNode)malloc(sizeof(node));if(q==0)returnfalse;
q->next=p->next;
p->next=q;
q->data=val;returntrue;}boolisempty(pNode head){if(head->next!=0)returnfalse;elsereturntrue;}intlenthlist(pNode head){int len=0;pNode p=head->next;while(p!=0){
p=p->next;
len++;}return len;}voidsortlist(pNode head){int len=lenthlist(head);
pNode p,q;for(p=head->next;p!=NULL;p=p->next){for(q=p->next;q!=NULL;q=q->next){if(p->data>q->data){int temp=p->data;
p->data=q->data;
q->data=temp;}}}}