一、单链表的创建、删除、插入、打印
1.声明一个结构体
#include <iostream> using namespace std; struct List { List *node; int n; };
2.创建
List *create(List *head) { int sum,i=1;; cout<<"输入总数:"<<endl; cin>>sum; List *p; List *Node =NULL; for(i=1;i<=sum;i++){ Node =new List; cin>>Node->n; if(head==NULL) { head=Node; } else p->node=Node; p=Node; if(i==sum) { p->node=NULL; } } return head; }
3.插入
List* insert(int n,List *head,int num){ List *p=NULL; List *q=NULL; p=head; int i=0; while(p!=NULL){ i++; if(i==n-1){ q=new List; q->n=num; q->node=p->node; p->node=q; } p=p->node; }
4.删除
List* delet(int n,List *head){ List *p=NULL; p=head; int i=1; if(n==1){ head=p->node; } else{ while(p!=NULL){ i++; if(i==n-1){ p->node=p->node->node; } p=p->node; } } return head; }
5.打印
void show(List *head) { List *p=NULL; p=head; while(p!=NULL) { cout<<p->n<<endl; p=p->node; } }
主函数测试:
int main() { List *student=NULL; student= create(student); show(student); student= delet(1,student); show(student); cout<<"*------------------*"<<endl; student=insert(2,student,8); show(student); return 0; }
时间: 2024-10-15 22:23:32