单链表头插尾插

头文件

#ifndef _HEAD_H
#define _HEAD_H

#define SIZE 10
#define FAILURE 10000
#define SUCCESS 10001

#include<stdlib.h>

typedef int elemtype;

struct node
{
    elemtype data;

    struct node *next;

};

typedef struct node Node;

int Linkinit(Node **head);
int insetr_head(Node *head, elemtype e);
int insert_tail(Node *head, elemtype e);
int traverse(Node *head, void (*p)(elemtype));

#endif

主函数

#include <stdio.h>
#include"head.h"
#include<time.h>

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

int main()
{
	int ret;
	elemtype e;
	Node *first = NULL;
	srand(time(NULL));
 
	ret = Linkinit(&first);
	if(ret == SUCCESS)
	{
		printf("Init success!\n");
	}
	else
	{
		printf("Init failure!\n");
	}
 
	int i;
	for(i = 0; i < SIZE; i++)
	{
		ret = insetr_head(first, rand() % 10);
		if(ret == SUCCESS)
		{
			printf("Insert Success!\n");
		}
		else
		{
			printf("Insert Failure!\n");
		}
	}
 
	ret = traverse(first, print);
	if(ret == FAILURE)
	{
		printf("TRVERSE Failure!\n");
	}
	else
	{
		printf("TRVERSE Success!\n");
	}
	
	
	return 0;
}
 
	

功能函数

/**************************************************************
  > File Name: head.c
  > Author: chengfeiyan
  > Mail: 1493789272@qq.com 
  > Created Time: 2018年08月07日 星期二 20时24分00秒
 **************************************************************/

#include"head.h"


int Linkinit(Node **head)
{
	*head = (Node *)malloc(sizeof(Node) * SIZE);
	
	if(NULL == *head)
	{
		return FAILURE;
	}
	
	(*head) -> next = NULL;
	
	return SUCCESS;
}

int insetr_head(Node *head, elemtype e)
{
	if( NULL == head)
	{
		return FAILURE;
	}
	
	Node *q = (Node *)malloc(sizeof(Node));
	
	q->data = e;
	q->next = head->next;
	head->next = q;
 
	return SUCCESS;
}

int insert_tail(Node *head, elemtype e)
{
	if( NULL == head)
	{
		return FAILURE;
	}
	
	Node *q = (Node *)malloc(sizeof(Node));
	
	
	while(head->next != NULL)
	{
		head = head->next;
	}
 
	q->data = e;
	q->next = head->next;
	head->next = q;
 
	return SUCCESS;
}


int traverse(Node *head, void (*p)(elemtype))
{
	if(head == NULL)
	{
		return FAILURE;
	}
 
	Node *q = head -> next;
 
	while(q)
	{
		p(q->data);
		q = q->next;
		
	}
	return SUCCESS;
}
	

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值