单链表结点插入

 

#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 Insert_List(Link pHead,Link Pointer,int num,char name[10])
{
 //创建新结点
 Link InsertNode=new Node;
 if(!InsertNode)
 {
  cout<<"Memory allocate failed\n";
  exit(-1);
 }
 InsertNode->num=num;
 strcpy(InsertNode->name,name);
 InsertNode->next=NULL;

 

 // 插入第一个结点
 if(NULL==Pointer)
 {
  InsertNode->next=pHead;
  return InsertNode;
 }

 

 else
 {
  //插入最后一个结点
  if(NULL==Pointer->next)
  {
   Pointer->next=InsertNode;
  }

  //插入中间结点
  else
  {
   InsertNode->next=Pointer->next;
   Pointer->next=InsertNode;
  }
 }
 return pHead;
}

 

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

 while(Pointer!=NULL)
 {
  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;
 }
 cout<<endl;
}

 

//释放链表
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);

 

 //插入结点
 while(1)
 {
  int position,new_num;
  char new_name[10];
  cout<<"\n请输入要插入的位置(输入-1结束插入):";
  cin>>position;

  //输入-1结束插入
  if(-1==position)
   break;

  else
  {
   Link Pointer=Find_List(pHead,position-1);
   cout<<"请输入新插入的学生编号:";
   cin>>new_num;
   cout<<"请输入新插入的学生姓名:";
   cin>>new_name;

   pHead=Insert_List(pHead,Pointer,new_num,new_name);
  }
 }

 

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

 

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

 

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值