带头节点的单链表(不含功能函数实现)

LinkList.h

#pragma once
#include 
#include 
#include 
#include 
#include 
using namespace std;

typedef int ElemType;

typedef struct SingleLinkedList
{
	ElemType data;
	struct SingleLinkedList* next;
}SLink;

//初始化链表--创建头节点
void InitLink(SLink** phead);

//创建新的节点
SLink* NewNode(ElemType e);

//打印链表
void PrintLink(SLink* phead);

//将数据输入到链表
void DataEntry(SLink** phead);

//链表的长度--遍历
int LengthtLink(SLink* phead);

//销毁单链表
void DestroyLink(SLink** phead);

LinkList.cpp

#include "LinkList.h"

//初始化链表--创建头节点
void InitLink(SLink** phead)
{
	*phead = (SLink*)malloc(sizeof(SLink));
	if (NULL == *phead)//申请内存是否失败
	{
		cout << strerror(errno) << endl;
		exit(-1);
	}
	(*phead)->data = -1;
	(*phead)->next = NULL;
}

//创建新的节点
SLink* NewNode(ElemType e)
{
	SLink* ps = (SLink*)malloc(sizeof(SLink));
	if (NULL == ps)//申请内存是否失败
	{
		cout << strerror(errno) << endl;
		exit(-1);
	}
	ps->data = e;
	ps->next = NULL;

	return ps;
}

//打印链表
void PrintLink(SLink* phead)
{
	assert(phead);//链表中无头节点
	SLink* p = phead->next;
	if (NULL == p)
	{
		cout << "单链表为空" << endl;
		return;
	}
	while (NULL != p)
	{
		cout << "[ " << p->data << " ] -> ";
		p = p->next;
	}
	cout << "NULL" << endl;
}

//将数据输入到链表
void DataEntry(SLink** phead)
{
	SLink* pstr = *phead;
	int n = 0;
	cout << "请输入数据个数: ";
	cin >> n;
	ElemType e = 0;
	cout << "请输入数据: " << endl;
	for (int i = 0; i < n; i++)
	{
		cin >> e;
		SLink* p = NewNode(e);
		pstr->next = p;
		pstr = p;
	}
}

//链表的长度--遍历
int LengthtLink(SLink* phead)
{
	assert(phead);
	SLink* pstr = phead->next;
	int count = 0;//计数
	while (pstr)
	{
		count++;
		pstr = pstr->next;
	}

	return count;
}

//销毁单链表
void DestroyLink(SLink** phead)
{
	assert(*phead);
	SLink* pstr = *phead;
	while (NULL != pstr)
	{
		SLink* pnext = pstr->next;
		free(pstr);
		pstr = pnext;
	}
	*phead = NULL;
}

你可能感兴趣的:(c语言,数据结构)