单链表的创建运算删除

#include <stdio.h>
#include <malloc.h>
#include <assert.h>
//#define DEBUG

typedef struct node{
  int data;
  struct node *next;
}Node,*Pnode;

//在p节点后面插入一个节点
void insert(Pnode p,int data)
{
  Pnode temp = NULL;
  temp = (Pnode)malloc(sizeof(Node));
  assert(temp);
  temp->data = data;
  temp->next = p->next;
  p->next = temp;
#ifdef DEBUG
  printf("insert\n");
#endif
}

//创建头节点
Pnode create_list()
{
  Pnode p = NULL;
  p = (Pnode)malloc(sizeof(Node));
  assert(p);
  p->data = 0;
  p->next = NULL;
#ifdef DEBUG
  printf("create_list\n");
#endif
  return p;
}

//在链表末尾插入一个节点
void apend(Pnode head,int data)
{
  Pnode tmp = NULL;
  Pnode temp = NULL;
  tmp = (Pnode)malloc(sizeof(Node));
  assert(tmp);
  temp = head;
  while (NULL != temp->next)
  {
    temp = temp->next;
  }
  temp->next = tmp;
  tmp->data = data;
  tmp->next = NULL;
#ifdef DEBUG
  printf("apend\n");
#endif
}

//在链表中找到data并把节点的指针返回
Pnode find(Pnode head,int data)
{
  Pnode temp = NULL;
  temp = head->next;
  while (data != temp->data)
  {
    if (NULL == temp->next)
    {
       return NULL;
    }
    temp = temp->next;
  }
#ifdef DEBUG
  printf("find\n");
#endif
  return temp;
}

//在链表中找到值为former的节点,并改为current
int change(Pnode head,int former,int current)
{
  Pnode temp = NULL;
  temp = head->next;
  while (former != temp->data)
  {
    if (NULL == temp->next)
    {
      printf("former is not found!\n");
    }
    temp = temp->next;
  }
  temp->data = current;
#ifdef DEBUG
  printf("change\n");
#endif
  return 0;
}

//删除p后面的一个节点
int delete_after(Pnode p)
{
  Pnode temp = NULL;
  temp = p->next->next;
  free(p->next);
  p->next = temp;
#ifdef DEBUG
  printf("delete_after\n");
#endif
  return 0;
}

//找到链表中data的节点,并删除该节点。
int delete_data(Pnode head,int data)
{
  Pnode tmp = NULL;
  Pnode temp = NULL;
  tmp = head->next;
  temp = head->next;
  while (data != temp->data)
  {
    if (NULL == temp->next)
    {
      printf("data is not found!\n");
    }
    temp = temp->next;
  }
  while (temp != tmp->next)
  {
    tmp = tmp->next;
  }
  tmp->next = temp->next;
  free(temp);
#ifdef DEBUG
  printf("delete_data\n");
#endif
  return 0;
}

//销毁链表(删除所有节点)
int destroy(Pnode head)
{
  Pnode tmp = NULL;
  Pnode temp = NULL;
  temp = head;
  while (NULL != temp->next)
  {
    tmp = temp;
    free(tmp);
    temp = temp->next;
  }
#ifdef DEBUG
  printf("destory\n");
#endif
  return 0;
}

//打印链表中所存的数据。
int print(Pnode head)
{
  Pnode temp = NULL;
  temp = head->next;
  if(NULL == head->next)
  {
    printf("Linklist is no data!\n");
  }
  while (NULL != temp->next)
  {
    printf("%d\n",temp->data);
    temp = temp->next;
  }
#ifdef DEBUG
  printf("print\n");
#endif
  return 0;
}

int test_link()
{

}

转载于:https://www.cnblogs.com/zhaopu/p/3198200.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值