當前位置:
首頁 >
数据结构实验二
發布時間:2025/5/22
19
豆豆
在不知道長度的前提下查找鏈表的中間節點:
#include"iostream" #include"stdio.h" #include"algorithm" #include"string.h" #include"cmath" #define maxsize 100 using namespace std; typedef int datatype; struct linklist //結點類型 {datatype data; //數據域linklist *next; //指針域 };void Initlist(linklist *&first) //鏈表初始化 {first=new linklist;//動態分配空間,如果出現錯誤則輸出 allocate errorif(first==NULL){cout<<"allocate error!"<<endl;}else{first->next=NULL;first->data=0;//記錄鏈表的長度,空著也是空著 } }void Clearlist(linklist *&first) //清空鏈表 {linklist *temp;while(first->next!=NULL){temp=first->next;first->next=temp->next;delete temp;//釋放掉temp所占的空間 } }void Inserttail2(linklist *&first,int number_a)//尾插法建表 {datatype x;linklist *tail,*temp=first;while(number_a--){cin>>x;tail=new linklist;if(tail==NULL) {cout<<"allocata error!"<<endl;exit(1);}tail->data=x;temp->next=tail;temp=tail;tail->next=NULL;}}linklist *findmid(linklist *&first) {linklist *temp1=first,*temp2=first->next;while(temp2!=NULL&&temp2->next!=NULL)//判斷條件缺一不可 {temp1=temp1->next;temp2=temp2->next->next;}if(temp1==first) return NULL;else return temp1; } int main() {int case_count=0;while(1){cout<<"案例"<<++case_count<<":"<<endl;linklist *la;int number_a;//記錄A和B集合中的元素個數 datatype a[maxsize];Initlist(la);cout<<"A集合中的元素個數:";cin>>number_a;if(number_a)cout<<"輸入A集合中的元素:";Inserttail2(la,number_a);linklist *mid_node=findmid(la);if(mid_node==NULL) cout<<"此鏈表為空!"<<endl<<endl;else{if(number_a%2)cout<<"中間節點元素的數域是:"<<mid_node->next->data<<endl<<endl;elsecout<<"中間節點元素的數域是:"<<mid_node->data<<"或 "<<mid_node->next->data<<endl<<endl;}}return 0; } View Code?
轉載于:https://www.cnblogs.com/acm-jing/p/4348419.html
總結
- 上一篇: eclipse运行时出现Unable t
- 下一篇: 一些工作情感