LinkList.h
#pragma once
#include <iostream>
#include <stdlib.h>
#include <assert.h>
#include <string.h>
#include <errno.h>
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;
}