单链表结点查找

来源:互联网 发布:python Image.new 编辑:程序博客网 时间:2024/05/18 09:16

 

#include <iostream>
using namespace std;

typedef class List
{
public:
 int num;
 char name[10];
 class List* next;
}Node,*Link;

 

//创建链表
Link Create_List(Link pHead)
{
 int n;
 cout<<"请输入学生人数:";
 cin>>n;

 //创建头结点
 pHead=new Node;
 if(!pHead)
 {
  cout<<"Memory allocate failed\n";
  exit(-1);
 }

 cout<<"\n请输入编号:";
 cin>>pHead->num;
 cout<<"请输入姓名:";
 cin>>pHead->name;
 pHead->next=NULL;

 

 //创建剩余结点
 Link Pointer=pHead;
 for(int i=1;i<n;i++)
 {
  Link newNode=new Node;

  if(!newNode)
  {
   cout<<"Memory allocate failed\n";
   exit(-1);
  }

  cout<<"请输入编号:";
  cin>>newNode->num;
  cout<<"请输入姓名:";
  cin>>newNode->name;
  newNode->next=NULL;

  Pointer->next=newNode;
  Pointer=newNode;
 }
 return pHead;
}

 

//查找链表结点
Link Find_List(Link pHead,int Key)
{
 Link Pointer=pHead;

 while(NULL!=Pointer)
 {
  if(Pointer->num==Key)
   return Pointer;

  Pointer=Pointer->next;
 }

 return Pointer;
}

 

//遍历输出链表
void Print_List(Link pHead)
{

 cout<<"\n编号\t姓名\n============"<<endl;

 Link Pointer=pHead;
 while(Pointer!=NULL)
 {
  cout<<"  "<<Pointer->num<<"\t"<<Pointer->name<<endl;
  Pointer=Pointer->next;
 }
}

 

//释放链表
void Free_List(Link pHead)
{
 while(pHead!=NULL)
 {
  Link Pointer=pHead;
  pHead=pHead->next;
  delete Pointer;
 }
}

 

int main()
{
 Link pHead=new Node;
 if(!pHead)
 {
  cout<<"Memory allocate failed\n";
  exit(-1);
 }

 //创建链表
 pHead=Create_List(pHead);

 //遍历输出链表
 Print_List(pHead);

 

 //查找结点
 while(1)
 {
  int key;
  cout<<"\n请输入要查找的学生编号(输入-1结束查找):";
  cin>>key;

  if(key!=-1)
  {
   Link Pointer=Find_List(pHead,key);
   if(!Pointer)
   {
    cout<<"\n没有找到!\n\n";
   }
   else
   {
    cout<<"\n编号\t姓名\n============"<<endl;
    cout<<"  "<<Pointer->num<<"\t"<<Pointer->name<<"\n\n";
   }
  }
  else
   exit(-1);
 }

 

 //释放链表
 Free_List(pHead);
 return 0;
}

 

0 0
原创粉丝点击