c语言链表的遍历、打印表长、找到元素打印、插入值x的操作函数

#include <stdio.h>
#include <stdlib.h>
 
/*节点结构制定*/
  typedef struct _st_node
    {int     data;
    struct   _st_node *next;
 }st_node;
    
 
/*操作函数声明*/
    int length(st_node *head);
    void travel_list(st_node *head);
    st_node *findkth(int k,st_node *head);
    st_node *findvalue(int n,st_node *head);
    st_node *insert(int x,int i,st_node *ptrl);
/*主函数:建表,调用操作函数*/
  
  int main(int argc,char**argv)
   {
     st_node    *head =NULL;
     st_node    *new_node;
     int        i;      
 
       for(i=0;i<10;i++)
     
        { new_node=malloc(sizeof(st_node));    
    
       if (NULL==new_node) {
         printf("malloc failure\n");
         return 0;
        }
            
       new_node->data=i+1;  
 
      if(head==NULL){
         head=new_node;
        }else{
             new_node->next = head;    
             head = new_node;
             }
    } 
  
   /*操作函数调用*/
  
    travel_list(head);
    length(head);
    findkth(8,head);
    findvalue(7,head);
    insert(48,5,head);
    return 0;
 }
      

   
 
/* 函数名:travel() 
 * 作用:头插法遍历,打印每一个data值*/
void travel_list(st_node *head)
   {   
     st_node  *node=head; 
     printf("头插法遍历\n");     
     while(node != NULL)
        
       {  
          printf("data:%d\n",node->data);
        node=node->next;
       }
        return;
    }  
 

   
/*函数名:length()
 * 作用:打印表长*/
 
int length(st_node *head)
{
   st_node* node=head;
   int j=0;
   while(node != NULL )
   {
     node=node->next;
     j++;
    }
   printf("\n打印表长:\nlength=%d\n",j);
   return ;
 }
 
 

   
 
/*函数名:findkth()
 * 作用:找到表中第k个元素的值并打印*/
 
st_node *findkth(int k,st_node *head)
 {
   st_node *node=head;
   int i=0;
  
   while(node!=NULL&&i<k)
   { node=node->next;
    i++;
    }
  
   if (i==k) 
 
 { printf("\n按序号查找:\nthe kth of NO.%d=%d\n",k,node->data);
 
 }
 
  else return NULL;
}
 
 
 
/*函数名:findevalue()
 * 作用:按值查找,是否有该值,有就输出*/
st_node *findvalue(int n,st_node *head)
  { 
   st_node *node = head;
   int i=1;
   while(node!=NULL&&(node->data)!=n)
   {  node=node->next;
      i++;
     }
   printf("data[%d]:findvalue=%d\n",i,node->data);
   return head ;
}
  
 
/*函数名:insert()
 * 作用:在第i个结点后插入一个值为x的新结点*/
 
st_node *insert(int x,int i,st_node *ptrl)
{
    st_node   *p,*new_one;     //创建新结点                
 
  if (i==0){                                  //新结点在表头
    new_one=(st_node*)malloc(sizeof(st_node)); //分配空间
    new_one->data=x;
    new_one->next=ptrl;
    return new_one;
    }
    
   p=findkth(i,ptrl);
   
   if (p==NULL){
          printf("error");
           return NULL;
   }
   else{
    new_one=(st_node*)malloc(sizeof(st_node));
    
    new_one->data=x;
    new_one->next = p->next;
    p->next=new_one;
    return ptrl;
 
   }
  
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值