数据结构实验二

在不知道长度的前提下查找链表的中间节点:

#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 error
    if(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;
        else
            cout<<"中间节点元素的数域是:"<<mid_node->data<<""<<mid_node->next->data<<endl<<endl;
    }
    }
    return 0;
}
View Code
原文地址:https://www.cnblogs.com/acm-jing/p/4348419.html