函数实现)"/>
链块串的实现(无功能函数实现)
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);//参数1:传的字符个数//打印串
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)//参数1:传的字符个数
{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;
}
更多推荐
链块串的实现(无功能函数实现)
发布评论