C语言链表的创建、插入、查找、删除、清空操作

1 篇文章 0 订阅
0 篇文章 0 订阅
 

#include "list.h"

#include <stdio.h>

#include <string.h>

#include <stdlib.h>

//创建头结点

Node* create_phead()

{       

         Node *phead=(Node*)malloc(sizeof(Node));

         phead->next=NULL;

         return phead;

}

//在末尾添加一个元素

void add_node(Node* phead,int d)

{

         Node* p=(Node*)malloc(sizeof(Node));

         p->data=d;

         p->next=NULL;

         Node*q=phead;

         while(q->next!=NULL)

         {

                   q=q->next;

         }

         q->next=p;

}

//getData –查找第n个元素的值

int getData(Node *phead,int n)

{

         int i=0;

         if(n<1) return 0;

         Node *p=phead;

         while(p->next!=NULL&&i<n)

         {

                   ++i;

                   p=p->next;

         //      printf("%d-%d\n",i,p->data);

         }

         return p->data;

}

//getByIndex –查找第n个结点

Node* getByIndex(Node *phead,int n)

{

         int i=0;

         if(n<1) return phead;

         Node *p=phead;

         while(p->next!=NULL&&i<n)

         {

                   ++i;

                   p=p->next;

         }

         return p;

}

//getPosition –查找元素d的位置,如果成功返回d的位置,不成功返回-1

 

int getPos(Node *phead,int d)

{

         Node *p=phead;

         int i=0;

         while(p->next!=NULL)

         {

                   ++i;

                   p=p->next;

                   if(d==p->data)

                   return i;

         }

         return -1;

}

//输出链表元素

void print(Node* phead)

{

         Node* q=phead;

         while(q->next!=NULL)

         {

                   q=q->next;

                   printf("%d\n",q->data);

         }

}

//移除第n个结点

void del_node(Node *phead,int n)

{

/*     Node *prev;

         Node *q=phead;

         int i=0;

         while(q->next!=NULL&&i<n)

         {

                   ++i;

                   prev=q;

                   q=q->next;

         }

         prev->next=q->next;

         free(q);

         q=NULL;

*/

         Node* prev=getByIndex(phead,n-1);

         Node* find=getByIndex(phead,n);

         prev->next=find->next;

         free(find);

         find=NULL;      

}

//链表清空

 void clear(Node *phead)

 {

   Node *q=NULL;

   while(phead!=NULL)

   {

     q=phead->next;

     phead->next=NULL;

     free(phead);

     phead=q;

   }

 }

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值