链表的基本操作(c链表实现)

#include<iostream>
#include<stdio.h>
#include<stdlib.h>
using namespace std;
typedef struct node{
        int data;
        struct node*next;
        }node;
node*tou(node*head,int num)//从头部插入num 
{
   node*p=NULL;
   p=(node*)malloc(sizeof(node));
   p->data=num;
   p->next=head->next;
   head->next=p;
   return head;
}
node*wei(node*head,int num)//从尾部插入num 
{
  node*p=NULL;
  node*l=NULL;
  l=head;
  while(l->next!=NULL)
    l=l->next;
  p=(node*)malloc(sizeof(node));
  p->data=num;
  p->next=NULL;
  l->next=p;
  return head;
}
 
node*insert(int i,node*head,int da)//在i位置插入da 
{
  node*p=head;
  int j=1;
  while(p&&j<i)
  {
    p=p->next;
    ++j;
  }
  if(!p||j>i) return 0;
  node*s=(node*)malloc(sizeof(node));
  s->data=da;
  s->next=p->next;
  p->next=s;
  return head;
}
void del(node *head,int num)//删除值为num的节点  
{  
     node *p=NULL; p=head;  
     node *pf=NULL;//记录p的前节点   
     while((p->next!=NULL)&&p->data!=num)  
     {  
         pf=p;  
         p=p->next;  
     }  
     if(p->next==NULL&&p->data!=num)  
          printf("不存在值为%d的节点",num);  
     else  
     {  
         pf->next=p->next;  
     }  
}  
int del1(node*head,int i) //删除i位置的节点 
{
     int da;
     node*p=NULL;p=head;
     node*q=NULL;
     int j=1;
     while((p->next!=NULL)&&j<i)
     {
      
       p=p->next;++j;
     }
     if((p->next==NULL)||j>i)
         cout<<"链表不存在"<<i<<"位置的节点"<<endl;
     else
      {
          da=p->next->data;
          q=p->next;p->next=q->next;
      } return da;
         
} 
int search(node*head,int i)
{
    int da;
    node*p=NULL;p=head->next;//p指向链表的第一个节点 
    int j=1;
    while(p!=NULL&&j<i) 
     {
       p=p->next;++j;
     }//直到i=j,p找到i位置,跳出循环
     if(p==NULL||j>i)
       cout<<"链表中此节点不存在"<<endl;
    da=p->data;
    return da;
}     
void out(node*head)//输出链表 
{
     node*temp=head->next;//注意是=head->next; 
     while(temp)
     {
       cout<<temp->data<<" ";
       temp=temp->next;
     }
}
int main()
{
     int sh1,sh2,x;node*p=NULL;char ch;int flag=0;
     node*head = (node *)malloc(sizeof(node));  
     head->next=NULL;//建立一个链表头
     p=head->next;
       
     int i;
   
   while(cin>>i)
    {    
         
       //tou(head,i);
         wei(head,i);
         out(head); 
         cout<<endl;
          
    }
      insert(3,head,8);out(head);cout<<endl;
      //del(head,5);out(head);cout<<endl;
      //sh1=del1(head,6);out(head);cout<<endl;
      //sh2=search(head,7);out(head);cout<<endl;cout<<sh2;cout<<endl;
      
     system("pause");
    return 0;
}
    
     
   

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值