链表头文件LinkList.h
#include <iostream>
#include <ctime>
using namespace std;
#define ERROR 0
#define OK 1
typedef int ElemType;
typedef int Status;
typedef struct Node{
ElemType data;
struct Node* next;
} Node;
typedef struct Node* LinkList;
void ShowMenu();
void ShowList(LinkList *head);
Status CreateWithHead(LinkList *head,int n);
Status GetMidNode(LinkList L,ElemType *e);
实现文件LinkList.cpp
#include "LinkList.h"
int main(){
int cmd;
ElemType e;
LinkList head;
ShowMenu();
cin>>cmd;
while(cmd){
switch(cmd){
case 1:
CreateWithHead(&head,11);
break;
case 2:
ShowList(&head);
break;
case 3:
GetMidNode(head,&e);
cout<<"\t\t中间节点为:"<<e<<endl;
break;
case 0:exit(0);break;
default:
exit(-1);
break;
}
ShowMenu();
cin>>cmd;
}
return 0;
}
void ShowMenu(){
char *str="\t\t****************************";
cout<<str<<endl;
cout<<"\t\t1.头插法"<<endl;
cout<<"\t\t2.显示列表"<<endl;
cout<<"\t\t3.获取中点"<<endl;
cout<<"\t\t0.退出"<<endl;
cout<<str<<endl;
}
void ShowList(LinkList *head){
int i=0;
LinkList p;
p=*head;
while(p->next){
if(i%5==0){
cout<<endl;
cout<<"\t\t";
}
cout<<p->data<<" ";
p=p->next;
i++;
}
cout<<endl;
}
Status CreateWithHead(LinkList *head,int n){
LinkList p;
int i;
srand(time(0));
*head=(LinkList)malloc(sizeof(Node));
(*head)->next=NULL;
for(i=0;i<n;i++){
p=(LinkList)malloc(sizeof(Node));
p->data=rand()%100+1;
p->next=*head;
*head=p;
}
return OK;
}
Status GetMidNode(LinkList L,ElemType *e){
LinkList search,mid;
search=mid=L;
while(search->next!=NULL){
if(search->next->next!=NULL){
search=search->next->next;
mid=mid->next;
}else{
search=search->next;
}
}
*e=mid->data;
return OK;
}