单链表的基本操作(代码优化)

#include <stdio.h>


typedef struct node {
   int data;
   struct node * next;
}linknode;


linknode * initlink(){                                                          //初始单链表
   linknode * head = (linknode *)malloc(sizeof(linknode));
   head->next=NULL;
   return head;
}


int adddata(linknode * head,int arr[] ,int n) {           //表尾增加数据
   int i;
   linknode * p1=NULL;
   linknode * p2=NULL;
   if(head==NULL) {
      head=initlink();
      p1=head;
   }
   else {
      p1=head;
      while(p1->next) {
          p1=p1->next;
      }
   }
   for(i=0;i<n;++i) {
     p2=(linknode *)malloc(sizeof(linknode));
     p2->data=arr[i];
     p1->next=p2;
     p1=p2;
   }
   p2->next=NULL;
   return 1;
}


void print(linknode * head) {             //打印数据
  linknode * p=NULL;
  if(head->next==NULL) {
     printf("empty linklist!");
  }
  p=head->next;
  while(p) {
     printf("%d\t",p->data);
     p=p->next;
  }
  printf("\n");
}




int delete(linknode * head,int value) {    //删除数据
    linknode * p1=NULL;
    linknode *p2=NULL;
    if(head->next==NULL) {
        return -1;
    }
    p1=head;
    p2=p1->next;
    while (p2 && p2->data!=value) {
       p1=p2;
       p2=p2->next;
    }
    if(p2){
      p1->next=p2->next;
      free(p2);
      return 1;
    }
    else 
        return -2;
 }


int length(linknode *head) {    //单链表数据长度
int size=0;
linknode * p=head;
if(head->next==NULL) {
        size=0;
    }
while(p->next) {
  size++;
  p=p->next;
 }
 return size;
}


int reverselist(linknode *head){  //单链表的逆置
   int size=0;
   size=length(head);
   linknode * p=NULL;
   linknode * q=NULL;
   if(size>1) {
     p=head->next;
     head->next=NULL;
     while(p) {
       q=p->next;
       p->next=head->next;
       head->next=p;
       p=q;
     }
   } 
   return 1;
}
int main(void) {
    int arr[]={1,2,3,4,12};
    int i;
    linknode * head=initlink();
    adddata(head,arr,5);
    print(head);
    i=delete(head,12);
    if(i==1) {
      print(head);
      printf("%d\n",length(head));
      reverselist(head);
      print(head);
    }
    else
      printf("delete failed!\n");
    return 1;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值