鏈表的建立插入與刪除


//file 鏈表的建立插入與刪除.cpp

#include"iostream.h"
#include"string.h"
#include"stdlib.h"

struct listnode{ //鏈表結點的類型聲明
 int num;
 char name[10];
 char sex[4];
 int age;
 int score;
 listnode* next;
};

listnode* head; //head指向表頭結點

listnode* createlist() //帶有空表頭的鏈表的建立
{
 listnode* temp,*tail; //tail指向當前鏈表的表尾結點
 
 head=new listnode;//建立空表頭
 if(head==NULL){
  cout<<"memory allocate fail and exit";
  exit(1);  
  }

 tail=head;
 tail->next=NULL;
 
 while(1){
   temp=new listnode;

   if(temp==NULL){
  cout<<"memory allocate fail and exit";
  exit(1);  
  }

   cout<<"輸入學生的信息(num,name,sex,age and score)(when num is -1 to stop!)/n";
   cin>>temp->num;

   if(temp->num==-1) break;

   else
   cin>>temp->name>>temp->sex>>temp->age>>temp->score;
  
  
   tail->next=temp;//在當前表尾後插入新結點temp
   tail=temp;
   tail->next=NULL;
 
 };
 
 delete temp;
 return head;
}


void browser(listnode* listhead)//”遍歷“鏈表的各個結點
{
 cout<<"/n各個學生的信息如下:/n";
 listnode* temp=listhead->next;
 while(temp!=NULL){
 cout<<temp->num<<" "
     <<temp->name<<" "
  <<temp->sex<<" "
  <<temp->age<<" "
  <<temp->score<<endl;
 
 temp=temp->next;
 }
}

int lenoflist(listnode* head) //求鏈表head的結點個數
{
 listnode* temp;
 temp=head->next;
 int lenofnode=0;

 while(temp!=NULL){
  lenofnode++;
  temp=temp->next;
 }

 return lenofnode;

}

listnode* insert(listnode* head,int num)
//在鏈表head的第num個結點之後插入一個新結點
{
 //判斷num的正確性
 if(num<0||num>lenoflist(head)){//when num=0,insert new node as the first node 
 cout<<"參數num錯誤!"<<endl;
    return head;
 }
 
 listnode* position=head;
 int counter=0;

 for(int k=0;k<num;k++) //求第num個結點位置position
 position=position->next;
 
 //在位置temp之後插入新結點
 cout<<"請輸入要插入的學生的信息(num,name,sex,age and score):/n";
 listnode* temp;  //temp用來保存要插入的學生信息
 temp=new listnode;
 cin>>temp->num>>temp->name>>temp->sex>>temp->age>>temp->score;

 //在position之後插入該結點
 temp->next=position->next;
 position->next=temp;

 return head;
 
}

listnode* deletenode(listnode* head,int num)
//刪除鏈表head中的第num個結點
{
 //判斷num的正確性
 if(num<1||num>lenoflist(head)){ 
 cout<<"參數num錯誤!"<<endl;
    return head;
 }
 
 listnode* position=head;

 for(int k=1;k<num;k++) //求第(num-1)個結點位置position
 position=position->next;
 
 //刪除第num個結點
 
 listnode* temp;  //temp用來保存要被刪除的結點
 temp=position->next;
 
 position->next=temp->next;
 delete temp;

 return head;
 
}


void main(void)
{
 head=createlist();

 cout<<"鏈表的長度爲"<<lenoflist(head)<<endl;

 browser(head);  //可以browser(createlist());

 cout<<"輸入插入到第幾個學生之後?";
 int num;
 cin>>num;

 browser(insert(head,num));

 cout<<"輸入要刪除第幾個學生?";
 cin>>num;

 browser(deletenode(head,num));

}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章