数据结构-单链表(list)

一、概述

队列是数据结构中最常用的一种算法,核心是FFO(First In First Out),即先进先出,顶部出队列,底部入队列。

二、操作

 

三、代码

头文件

#ifndef _LIST_H_
#define _LIST_H_
#include <stdio.h>
#include <stdlib.h>

#define SUCCESS		0
#define FAIL	   -1
//链表的数据结构
typedef struct ListNode *pListNode;
typedef int DataType;//链表中的数据类型 
 
typedef struct ListNode{
	DataType *data;
	pListNode next; 
}sListNode;

typedef struct List{
	sListNode *head;
	int dataNum;
}sList;

void InitList();
int Insert(const DataType data);
int Delete(const DataType data);
int Query(const DataType *data); 
void Clear();
int Size();
void Print();
#endif

源文件

#include "list.h"
#include <string.h>

static sList gList;

static void DataCopy(DataType *newData, const DataType *oldData){
	memcpy(newData,oldData,sizeof(DataType));
}

static int DataCmp(DataType *newData, const DataType *oldData){
	return memcmp(newData,oldData,sizeof(DataType));
}

void InitList(){
	gList.dataNum = 0;
	gList.head = NULL;
}
 
int Insert(const DataType data){
	pListNode node = (pListNode)malloc(sizeof(sListNode));
	node->data = (DataType *)malloc(sizeof(DataType));
	DataCopy(node->data,&data);
	node->next = NULL;
	
	if(NULL == gList.head)
	{
		gList.head = node;
	}
	else
	{
		node->next = gList.head;
		gList.head = node;
	}
	
	gList.dataNum++;
	return SUCCESS;	
}
 
int Delete(const DataType data){
	if(NULL == gList.head){
		return FAIL;
	}

	pListNode head = gList.head;
	pListNode next = NULL;	
		
	if(0 == DataCmp(gList.head->data,&data))
	{
		gList.head = head->next;
		free(head->data);
		free(head);
		gList.dataNum--;
		return SUCCESS;
	}
	else
	{
		next = head->next;
		
		while(next){
			if(0 == DataCmp(next->data,&data))
			{
				head->next = next->next;
				free(next->data);
				free(next);
				gList.dataNum--;
				return SUCCESS;				
			}
			
			head = next;
			next = head->next;
		}
	}
	
	return FAIL;	
}
 
int Query(const DataType *data){
	pListNode node = gList.head;
	
	while(node){
		if(0 == DataCmp(node->data,data)){
			return SUCCESS;
		}
	}
	
	return FAIL;
}
 
void Clear(){
	pListNode node = NULL;
	 
	while(gList.head)
	{
		node =  gList.head;
		gList.head = gList.head->next;
		free(node->data);
		free(node);		
	}
	
	InitList();
}

int Size(){
	return gList.dataNum;
}

void Print(){
	pListNode node = gList.head;
	printf("size:%d\n",gList.dataNum);
	
	while(node)
	{
		printf("%d ",*node->data);
		node = node->next;	
	}
	
	printf("\n");	
}

测试文件

#include <stdio.h>
#include <stdlib.h>
#include "list.h"
/* run this program using the console pauser or add your own getch, system("pause") or input loop */

int main(int argc, char *argv[]) {
	InitList();
	Insert(1);
	Insert(2);
	Print();
	Delete(2);
	Print();
	Delete(1);
	Print();	
	return 0;
}

测试结果

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值