链表的一个简单应用---目录下的文件并排序

</pre><pre name="code" class="html">/*  2015-1-13  [watchmen 数据结构和算法 01-链表和数组] 
**  链表的一个简单应用,读取目录下的文件及子文件名并排序
**  (a)  不知道这个目录下有多少个子文件和目录
**  (b)  读取目录下的子目录条目.opendir 打开目录  readdir 从目录中读取一个文件项, 读取的顺序不是排列好的
**   选择链表来存储是不错的选择. 动态的增加节点数, 在中途中添加新的节点. 链表方便操作
*/
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include <dirent.h>
#include <string.h>

typedef struct list
{
	char *name;
	struct list *next;
}linknode, *linklist;

linklist insert_local(linklist head, linklist newnode)
{
	assert(newnode);
	linklist temp = head;
	
	if(temp == NULL)
	{//空链表
		head = newnode;
		return head;
	}
	
	if(strcmp(temp->name,newnode->name) > 0)
	{//插入head处
		newnode->next = temp;
		head = newnode;
		return head;
	}
	
	linklist prev = head;
	temp = head->next;
	
	while(temp != NULL)
	{//不断循环查找应该放入的位置
		if(strcmp(newnode->name,temp->name) > 0
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
要将图书管理系统的文件存入链表,需要进行以下步骤: 1. 定义一个图书的结构体,包含图书的相关信息,例如书名、作者、ISBN等。 2. 创建一个链表节点的结构体,包含一个指向图书结构体的指针和一个指向下一个链表节点的指针。 3. 创建一个链表的头节点,并初始化为NULL。 4. 打开图书管理系统的文件,读取每一本图书的信息。 5. 为每一本图书创建一个链表节点,并将读取到的图书信息存入该节点的图书结构体中。 6. 将新创建的链表节点插入到链表中合适的位置,可以按照图书的ISBN号进行排序。 7. 重复步骤4-6,直到读取完所有的图书信息。 8. 关闭文件。 以下是一个示例代码,用于将图书管理系统的文件存入链表(假设文件中每行记录包含图书的名称和作者,以逗号分隔): ```c #include <stdio.h> #include <stdlib.h> #include <string.h> // 定义图书结构体 typedef struct { char name[100]; char author[100]; } Book; // 定义链表节点结构体 typedef struct Node { Book book; struct Node* next; } Node; // 插入新节点到链表中 void insertNode(Node** head, Book book) { Node* newNode = (Node*)malloc(sizeof(Node)); newNode->book = book; newNode->next = NULL; if (*head == NULL) { *head = newNode; } else { Node* current = *head; Node* previous = NULL; while (current != NULL && strcmp(book.name, current->book.name) > 0) { previous = current; current = current->next; } if (previous == NULL) { newNode->next = *head; *head = newNode; } else { previous->next = newNode; newNode->next = current; } } } // 打印链表中的图书信息 void printList(Node* head) { Node* current = head; while (current != NULL) { printf("书名:%s,作者:%s\n", current->book.name, current->book.author); current = current->next; } } int main() { Node* head = NULL; FILE* file = fopen("books.txt", "r"); if (file == NULL) { printf("无法打开文件!\n"); return 1; } char line[200]; char name[100], author[100]; while (fgets(line, sizeof(line), file)) { sscanf(line, "%[^,], %[^\n]", name, author); Book book; strcpy(book.name, name); strcpy(book.author, author); insertNode(&head, book); } fclose(file); printList(head); return 0; } ``` 请注意,此代码仅提供了一个基本的示例,实际应用中可能需要根据具体需求进行调整和扩展。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值