摘要:C/C++ 数据结构
正文:用链式结构来实现电话号码查询系统,程序如下:
#include<iostream>
#include<malloc.h>
#include<stdlib.h>
#include<stdio.h>
#include<cstring>
using namespace std;
typedef struct Node
{
char name[10];
char phoneNumber[12];
struct Node *next;
}ListNode;
//函数声明
ListNode *CreateList(int n);//创建
void InseartList(ListNode *h,int i,char name[],char phoneNumber[],int &n);//头插法插入
void DeleteList(ListNode *h,int i,int &n); //删除
void OutList(ListNode *h);//显示
ListNode *InitList(void);//初始化
ListNode *InitList(void)
{
ListNode *head;
head=(ListNode*)malloc(sizeof(ListNode));
if(head==NULL) exit (1);
head->next=NULL;
return head;
}
//主函数
void main()
{
ListNode *h;
ListNode *InitList(void);
int i,n;
char phoneNumber[12];
char name[10];
while(1){
cout<<"1.建立号码表"<<endl;
cout<<"2.插入用户信息"<<endl;
cout<<"3.删除用户信息"<<endl;
cout<<"4.显示当前信息"<<endl;
cout<<"0.退出"<<endl;
cout<<"请输入相应的操作:"<<endl;
cin>>i;
switch(i)
{
case 1:
{
cout<<"请输入结点个数:"<<endl;
cin>>n;
h=CreateList(n);
break;
}
case 2:
{
cout<<"请输入您要插入信息的位置:"<<endl;
cin>>i;
cout<<"请输入电话号码:"<<endl;
cin>>phoneNumber;
cout<<"请输入用户姓名:"<<endl;
cin>>name;
InseartList(h, i,name,phoneNumber, n);
//+n+;//结点增1
break;
}
case 3:
{
cout<<"请输入要删除的位置"<<endl;
cin>>i;
DeleteList(h,i,n);
//n--;//结点减1
break;
}
case 4:
{
OutList(h);
break;
}
case 0:
{
cout<<"感谢使用,再见!"<<endl;break;
}
}
}
}
//函数定义
//创建
ListNode *CreateList(int n)
{
ListNode *head,*p,*pre;
int i;
head=(ListNode*)malloc(sizeof(ListNode));
head->next=NULL;
pre=head;
for(i=1;i<=n;i++)
{
cout<<"输入第"<<i<<"个用户的姓名"<<endl;
p=(ListNode*)malloc(sizeof(ListNode));
cin>>p->name;
cout<<"输入第"<<i<<"个用户的电话号码"<<endl;
cin>>p->phoneNumber;
pre->next=p;
pre=p;
}
p->next=NULL;
return head;
}
//显示
void OutList(ListNode *h)
{
ListNode *p;
p=h->next;
while(p)
{
cout<<p->name<<": "<<p->phoneNumber<<endl;
p=p->next;
cout<<endl;
}
}
//头插法插入
void InseartList(ListNode *h,int i,char name[],char phoneNumber[],int &n)
{
ListNode *q,*p;
int j;
if(i<1||i>n+1)
cout<<"插入位置有误!"<<endl<<endl;
else
{
j=0;p=h;
while(j<i-1)
{
p=p->next;
j++;
}
q=(ListNode*)malloc(sizeof(ListNode));
strcpy(q->name, name);
strcpy(q->phoneNumber,phoneNumber);
q->next=p->next;
p->next=q;
n++;
}
}
//删除
void DeleteList(ListNode *h,int i,int &n)
{
ListNode *p,*q;
int j;
char name[10];
char phoneNumber[12];
if(i<1||i>n)
cout<<"您的输入有误,请重新输入!\n";
else
{
j=0;p=h;
while(j<i-1)
{
p=p->next;
j++;
}
q=p->next;
p->next=q->next;
strcpy(name, q->name);
strcpy(phoneNumber,q->phoneNumber);
free(q);
n--;
}
}