单链表头插尾插

头文件

#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: [email protected] 
  > 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;
}
	

猜你喜欢

转载自blog.csdn.net/GX0401/article/details/81488952