单链表的基本操作

#include<iostream>
#include<cstdio>
#include<cstdlib>
  using namespace std;
 typedef struct node
 {
  struct node *next;
  int data;
 }*List;
 

 void initList(List *L)
 {
  *L=(node*)malloc(sizeof(node));
  (*L)->next=NULL;
 }
 //创建单链表 前插法 
 void FrontCreateList(List L,int n)
 {
  node *p;
    // L=(node*)malloc(sizeof(node));
  //L->next=NULL;
  for(int i=0;i<n;i++)
  {
     p=(node*)malloc(sizeof(node));
     cin>>p->data;
     p->next=L->next;
       L->next=p;
  }
 }
 
 //尾插法创建单链表 
  void rearCreateList(List L,int n)
  {
    node *r,*s;
  // L=(node *)malloc(sizeof(node));动态指针指向链表的表当前表尾, 
    r=L;
    for(int i=0;i<n;i++)
    {
    s=(node *)malloc(sizeof(node));
    cin>>s->data;
    r->next=s;
    r=s;
    } 
    r->next=NULL;   
  }
  //插入链表元素 
 void insertList(List L,int i,int *e)
 {
 
  node *s,*p;
  p=L->next;
  int j=1;
  while(j<i&&p!=NULL)
  {
     p=p->next;
     j++;
  }
    
    s=(node *)malloc(sizeof(node));
    s->data=*e;
    s->next=p->next;
    p->next=s;
   
 }
 
 //删除链表元素 
 void DeleteList(List L,int i)
 {
  node *p,*r;
  p=L->next;
  int j=1;
  while(j<i)
  {
  p=p->next;
  j++;
  }
  r=p->next;
  p->next=r->next;
  free(r);
 
 } 
  //得到链表长度 
  int GetListlengthe(List L)
  {
  node *s;
  s=L->next;
  int j=0;
  while(s)
  {
  j++;
  s=s->next;
  }
  return j;
  }
  //判断链表是否为空 
  bool Listisempty(List L)
  {
   
  if(L->next==NULL)
  {
  return true;
  }
  else  return false;
  }
  //查询链表元素 
  void SearchlistElement(List L,int k)
  {
    node *s;
    s=L->next;
    while(s!=NULL)
    {    
     if(s->data==k)
     {
      cout<<"已找到"<<endl; 
      break;
     }
     s=s->next; 
    }
   if(s==NULL)  cout<<"未找到";  
    
  }
  //打印链表元素 
 void PrintList(List L)
 {
     node *p;
     p=L->next; 
     while(p)
     {
      cout<<p->data<<" ";
      p=p->next;
     }
     cout<<endl;
 }
 
 int main()
 {
  List L;
    initList(&L);
  int n;
  cin>>n;
    rearCreateList(L,n);
    PrintList(L);
    
    FrontCreateList(L,n);
    PrintList(L);
    cout<<GetListlengthe(L);*/
    cout<<GetListlengthe(L)<<endl; 
     int e=5;
    if(Listisempty(L))cout<<"yes"; 
    else  cout<<"no";  
SearchlistElement(L,3);
int e=10;
  insertList(L,2,&e); 
  PrintList(L);*/
  DeleteList(L,3);
  PrintList(L);
  return 0;
 }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值