单链表头插法和尾插法的实现

#ifndef _LINKLIST_H
#define _LINKLIST_H

#define FAILURE    10000
#define SUCCESS    10001
#define TRUE       10002
#define FALSE      10003
typedef int ElemType; 

struct node
{
    ElemType data;   //数据域
    struct node *next;   //指针域
};

typedef struct node Node;
#endif
#include <stdio.h>
#include <stdlib.h>
int LinkInit(Node **l)      //初始化
{
    *l=(Node *)malloc(sizeof(Node)*1);
    if(NULL == *l)
    {
        return FAILURE;
    }
    (*l)->next=NULL;
    return SUCCESS;
}
/*
   int LinkInsert(Node *l,ElemType e)     //头插法 
   {
   Node *p=l;

   if(NULL == l)
   {
   return FAILURE;
   }
   Node *q = (Node *)malloc(sizeof(Node)*1);  //要插入的
   q->data=e;
   Node *t = p->next;
   p->next = q;
   q->next = t;

   }
   */




int LinkInsert(Node *l,ElemType e)     //头插法
{
    Node *p=l;
    int k=1;
    if(NULL == l)
    {
        return FAILURE;
    }
    Node *q=(Node *)malloc(sizeof(Node)*1);  //要插入的
    while(k < 1 || p == NULL)
    {
        p = p->next;
        k++;
    }
    if(k > 1 || p == NULL)
    {
        return FAILURE;
    }
    if(NULL == q)
    {
        return FAILURE;
    }
    q->data = e;
    Node *t = p->next;
    p->next = q;
    q->next = t;

}
int LinkTraverse(Node *l,void (*p)(ElemType))
{
    if(NULL == l)
    {
        return FAILURE;
    }
    Node *q = l;
    while(q->next)
    {
        q = q->next;
        p(q->data);
    }
    return SUCCESS;
}

void print(ElemType e)
{
    printf("%d ", e);
}

int main()
{
    int ret, i;
    srand(time(NULL));
    Node *first = NULL;   //头指针

    srand(time(NULL));

    ret = LinkInit(&first);
    if (ret == FAILURE)
    {
        printf("Init Failure!\n");
    }
    else
    {
        printf("Init Success!\n");
    }

    for (i = 0; i < 10; i++)
    {
        ret = LinkInsert(first, rand() % 20);
        if (ret == FAILURE)
        {
            printf("Insert Failure!\n");
        }
        else
        {
            printf("Insert Success!\n");
        }
    }

    ret = LinkTraverse(first, print);
    if (ret == FAILURE)
    {
        printf("\nTraverse Falure!\n");
    }
    else
    {
        printf("\nTraverse Success!\n");
    }
    return 0;
}

头插法: 

 尾插法:

 

 

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值