当前位置: 首页 > news >正文

数据结构链串的简单代码实现(C语言代码版)

注:本代码只限于简单,目前只考虑字符单个输入情况

#include <stdio.h>  
#include <stdlib.h>  // 定义链串的节点  
typedef struct Node {  char data;          // 节点存储的字符  struct Node* next;  // 指向下一个节点的指针  
} Node;  // 定义链串的结构体  
typedef struct {  Node* head;         // 指向链串第一个节点的指针  int length;         // 链串的长度  
} LinkString;  // 创建一个新的链串节点  
Node* createNode(char data) {  Node* newNode = (Node*)malloc(sizeof(Node));  if (newNode == NULL) {  fprintf(stderr, "Memory allocation failed\n");  exit(EXIT_FAILURE);  }  newNode->data = data;  newNode->next = NULL;  return newNode;  
}  // 初始化链串  
void initLinkString(LinkString* ls) {  ls->head = NULL;  ls->length = 0;  
}  // 在链串末尾添加字符  
void appendChar(LinkString* ls, char c) {  Node* newNode = createNode(c);  if (ls->head == NULL) {  ls->head = newNode;  } else {  Node* temp = ls->head;  while (temp->next != NULL) {  temp = temp->next;  }  temp->next = newNode;  }  ls->length++;  
}  // 打印链串  
void printLinkString(LinkString* ls) {  Node* temp = ls->head;  while (temp != NULL) {  printf("%c", temp->data);  temp = temp->next;  }  printf("\n");  
}  // 释放链串占用的内存  
void freeLinkString(LinkString* ls) {  Node* temp;  while (ls->head != NULL) {  temp = ls->head;  ls->head = ls->head->next;  free(temp);  }  ls->length = 0;  
}  int main() {  LinkString ls;  initLinkString(&ls);  // 向链串中添加字符  appendChar(&ls, 'H');  appendChar(&ls, 'e');  appendChar(&ls, 'l');  appendChar(&ls, 'l');  appendChar(&ls, 'o');  // 打印链串  printLinkString(&ls);  // 释放链串占用的内存  freeLinkString(&ls);  return 0;  
}


http://www.mrgr.cn/news/18002.html

相关文章:

  • HarmonyOS开发实战( Beta5版)多线程能力场景化示例最佳实践
  • 如何提升网站在Google的排名?
  • SAP自动化操作
  • 2 html5 浏览器已经支持的新API
  • 英特尔或将计划剥离资产削减成本
  • 护栏碰撞监测系统:多场景应用与成功实践案例解析
  • 利用Go语言模拟实现Raft协议
  • Apache CloudStack Official Document 翻译节选(十三)
  • 【函数模板】函数模板的特化
  • 【数据结构-二维前缀和】【列维护优化】力扣3212. 统计 X 和 Y 频数相等的子矩阵数量
  • vue 批量导出pdf 压缩包 zip
  • 设计模式—2—单例模式
  • 使用Proxifer和Burpsuite软件搭配对小程序做渗透测试
  • 心理咨询展示型网站渠道拓展服务
  • 【react】开发一些简单的业务表单可复用组件,需要注意哪些细节
  • Unity(2022.3.41LTS) - UI详细介绍-TMP
  • 【hot100篇-python刷题记录】【课程表】
  • 车窗边缘上的装饰边和花点的作用
  • chapter11-枚举和注解——(枚举类)——day14
  • [矩阵快速幂] 爬楼梯