數據結構初學
阿新 • • 發佈:2017-05-08
col () truct let namespace pan nbsp insert new
一、單鏈表的創建、刪除、插入、打印
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; }
數據結構初學