單鏈表的常用基本操作

//單鏈表的常用基本操作.cpp

#include<iostream>
using namespace std;

typedef struct Node{
 char name[10];
 int age,score;
 struct Node* next;
}ListNode;

ListNode* Create_emptylist(void)   //創建空鏈表,帶頭結點------------1
{
  ListNode *temp=new ListNode;
  temp->next=NULL;
  return temp;
}


void Insert_list(ListNode *list,ListNode *pos,ListNode x) // 在pos後插入x-------------2
{
 if(list==NULL) {
  cout<<"list is empty!"<<endl;
  return;
 }

 if(pos==NULL){
  cout<<"Error position found!/n";
  return;
 }

 ListNode *temp=new ListNode;

 strcpy(temp->name,x.name);
 temp->age=x.age;
 temp->score=x.score;
 
 temp->next=pos->next;
 pos->next=temp;
}

void Delete_list(ListNode* list,ListNode* pos) //刪除pos之後的結點-------------3
{
 if(list==NULL){
  cout<<"list is empty!"<<endl;
  return;
 }

 if(pos==NULL){
  cout<<"Error position found!/n";
  return;
 }

   if(pos->next==NULL){
  cout<<"No node after the postion!/n";
  return;
 }

   ListNode *temp=pos->next;
   pos->next=temp->next;
   delete temp;
}

int Get_length(ListNode* list)    //計算鏈表長度(元素個數)----------4
{
 ListNode* tail=list;
 int length=0;
 while(tail->next!=NULL){
  length++;
  tail=tail->next;
 }
 
 return length;
}

ListNode* Get_position(ListNode* list,int order)  //根據元素所在的位序,得到其位置值----5
{
 if(! (order>=1 && order<=Get_length(list)) ){
  cout<<"Error order found/n";
  return NULL;
 }

 ListNode* t=list->next;
 int num=1;

 while(num<order){
  num++;
  t=t->next;
 }
 
 return t;
}

void browser(ListNode *list)  //遍歷鏈表(輸出各元素值)-------6
{
 ListNode *t=list->next;
 cout<<"/nBrowsing the list:/n";
 while(t!=NULL){
  cout<<t->name<<","<<t->age<<","<<t->score<<endl;
  t=t->next;
 }

}

ListNode* Get_tail(ListNode* list) //得到鏈表的尾結點位置-----7
{
 ListNode* tail=list;
 while(tail->next!=NULL)
  tail=tail->next;

 return tail;
}

void Delete_list_order(ListNode* list,int order) //刪除單鏈表中指定序號的元素-----8
{
   ListNode* pos=Get_position(list,order); //該元素的位置
   ListNode* pre=list;

   while(pre->next!=pos)   pre=pre->next;  //求該元素的前驅結點的位置

   Delete_list(list,pre);
 }

 

void main(void)
{
 ListNode *mylist;
 mylist=Create_emptylist();

  
    ListNode * tail=Get_tail(mylist);

    for(int k=1;k<=3;k++){  //創建三個元素組成的鏈表
  ListNode temp;
  temp.next=NULL;

  cout<<"/ninput the name:";
  cin>>temp.name;

     cout<<"input the age:";
  cin>>temp.age;

        cout<<"input the score:";
  cin>>temp.score;

        Insert_list(mylist,Get_tail(mylist),temp);
  
 }

    browser(mylist);
 cout<<"the length of the list is "<<Get_length(mylist)<<endl;

 Delete_list(mylist, Get_position(mylist,2) );
 cout<<"after delete the node after No.2/n";
 cout<<"the length of the list is "<<Get_length(mylist)<<endl;
 browser(mylist);

    Delete_list_order(mylist,1);
 cout<<"after delete the first node:/n";
 cout<<"the length of the list is "<<Get_length(mylist)<<endl;
 browser(mylist);
}


 
 

發佈了36 篇原創文章 · 獲贊 0 · 訪問量 7萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章