下面的代码实现了链表的创建,初始化,加入新节点,读取数据.
/*设置节点*/
struct node
{
struct node *next;
char *data;
struct node *prev;
};
/*
初始化链表
返回了一个data为字符newdata的头节点
*/
struct node *list_init(char *newdata)
{
//名义头节点
struct node *head = malloc(sizeof(struct node));
head->data = newdata;
head->next = head;
head->prev = head;
return head;
}
//写入数据并创建新节点
struct node *newnode(char *newdata)
{
struct node *new = malloc(sizeof(struct node));
new->data = newdata;
new->next = NULL;
new->prev = NULL;
}
//将节点加入链表
int addnode(struct node *new,struct node *tail)
{
new->prev = tail->prev;
new->next = tail;
tail->prev = new;
new->prev->next = new;
}
struct node *list = list_init("1.mp3");
char *path = "/mnt/udisk/MusicJF/";
DIR *dp = opendir(path);
struct dirent *p;
while(p = readdir(dp)) //遍历目录文件
{
if(p->d_type == DT_REG)
{
if(strstr(p->d_name,".mp3")) //判断是否为.mp3文件
{
struct node *new = newnode(p->d_name); //创建新节点
addnode(new,list); //插入新节点
}
}
}
char buf[200];
//头指针
struct node *head = list->next;
总结:
- 链表的定义,由三部分组成:前驱,数据,后继。
- 链表需要初始化,即:赋予头节点一个数据,前驱和后继都先为null
- 创建新节点:其实和初始化一样,创建一个有数据的游离节点。
- 加入新节点:将游离节点与头节点相连。链表的增加有前加和后加。这里的代码是往前加。