String.h
#pragma once
#include <stdlib.h>
#include <assert.h>
#include <string.h>
#include <errno.h>
#include <iostream>
using namespace std;
#define SIZE 5
#define EFF_SIZE (SIZE -1)
typedef char elemType;
typedef struct node
{
elemType str[SIZE];
struct node* next;
}node;
typedef struct String
{
node* head;
node* tail;
int length;
}String;
void initString(String* ps);
node* newNode(int size, char* str);
void printString(const String* s);
void enterData(String* ps, char* ch);
void destroyString(String* ps);
String.cpp
#include "String.h"
void initString(String* ps)
{
node* p = (node*)malloc(sizeof(node));
if (NULL == p)
{
cout << strerror(errno) << endl;
exit(-1);
}
p->next = NULL;
ps->head = ps->tail = p;
ps->length = 0;
}
node* newNode(int size, char* str1)
{
node* p = (node*)malloc(sizeof(node));
if (NULL == p)
{
cout << strerror(errno) << endl;
exit(-1);
}
for (int i = 0; i < EFF_SIZE; i++)
{
if (size <= i)
{
p->str[i] = '#';
}
else
{
p->str[i] = str1[i];
}
}
p->str[EFF_SIZE] = '\0';
p->next = NULL;
return p;
}
void printString(const String* ps)
{
assert(ps);
node* p = ps->head->next;
if (NULL == p)
{
cout << "串无数据" << endl;
return;
}
while (p)
{
cout << "[ ";
if (ps->tail == p)
{
for (int i = 0; i < SIZE; i++)
{
if ('#' == p->str[i])
{
break;
}
cout << p->str[i];
}
}
else
{
cout << p->str;
}
cout << " ]->";
p = p->next;
}
cout << "NULL" << endl;
}
void enterData(String* ps, char* ch)
{
assert(ps);
node* cur = ps->head;
int leng = strlen(ch);
ps->length = leng;
int n = leng / EFF_SIZE;
int count = 0;
if (0 != leng % EFF_SIZE)
{
count = leng - n * EFF_SIZE;
n++;
}
for (int i = 1; i <= n; i++)
{
node* p = NULL;
if (i == n && 0 != count)
{
p = newNode(count, ch + (i - 1) * EFF_SIZE);
}
else
{
p = newNode(EFF_SIZE, ch + (i - 1) * EFF_SIZE);
}
ps->tail = cur->next = p;
cur = p;
}
}
void destroyString(String* ps)
{
node* pcur = ps->head;
while (pcur)
{
node* pnext = pcur->next;
free(pcur);
pcur = pnext;
}
ps->head = ps->tail = NULL;
ps->length = 0;
}