|
5鱼币
实在那一看懂,求解!!!
忘懂的人回复详解一下,,,急!!急!!急!!
1. llist.c
#include <stdlib.h>
#include <string.h>
#include "llist.h"
#if 0
struct llist_node_st {
void *data;
struct llist_node_st *prev;
struct llist_node_st *next;
};
typedef struct {
int size;
struct llist_node_st head;
} LLIST;
#endif
LLIST *llist_creat(int size)
{
LLIST *new;
new = malloc(sizeof(*new));
if (new == NULL) {
return NULL;
}
new->size = size;
new->head.next = new->head.prev = &new->head;
return new;
}
void llist_destroy(LLIST *);
int llist_add(LLIST *ptr, const void *data, int dir)
{
struct llist_node_st *newnode;
newnode = malloc(sizeof(*newnode));
if (newnode == NULL) {
goto malloc_node_err;
}
newnode->data = malloc(ptr->size);
if (newnode->data == NULL) {
goto malloc_data_err;
}
memcpy(newnode->data, data, ptr->size);
if (dir == LLIST_ADD_FORWARD) {
newnode->next = ptr->head.next;
newnode->prev = &ptr->head;
} else {
newnode->next = &ptr->head;
newnode->prev = ptr->head.prev;
}
newnode->next->prev = newnode;
newnode->prev->next = newnode;
return 0;
free(newnode->data);
malloc_data_err:
free(newnode);
malloc_node_err:
return -1;
}
//llist_delet(LLIST *, );
//llist_find(LLIST *, );
void llist_travel(LLIST *ptr, llist_op *op)
{
struct llist_node_st *cur;
for (cur = ptr->head.next; cur != &ptr->head; cur = cur->next) {
op(cur->data);
}
}
2. llist.h
#ifndef HS_LLIST_H
#define HS_LLIST_H
#define LLIST_ADD_FORWARD 0
#define LLIST_ADD_BACKWARD 1
typedef void llist_op(void *);
struct llist_node_st {
void *data;
struct llist_node_st *prev;
struct llist_node_st *next;
};
typedef struct {
int size;
struct llist_node_st head;
} LLIST;
LLIST *llist_creat(int size);
void llist_destroy(LLIST *);
int llist_add(LLIST *, const void *data, int dir);
//llist_delet(LLIST *, );
//llist_find(LLIST *, );
void llist_travel(LLIST *, llist_op *op);
#endif /* HS_LLIST_H */
3. main.c
#include <stdio.h>
#include "llist.h"
#define NAMESIZE 32
struct score {
int id;
char name[NAMESIZE];
int ch;
int math;
int en;
};
static void print_score(void *data)
{
struct score *d = data;
printf("%d %s %d %d %d\n", d->id, d->name, d->ch, d->math, d->en);
}
int main(void)
{
struct score tmp;
LLIST *list;
int i;
list = llist_creat(sizeof(struct score));
/* if error */
for (i = 0; i < 9; i++) {
tmp.id = i;
tmp.ch = 100 - i;
tmp.math = 100 - i * 2;
tmp.en = 100 - i * 3;
snprintf(tmp.name, NAMESIZE, "stu%d", i);
llist_add(list, &tmp, LLIST_ADD_FORWARD);
}
llist_travel(list, print_score);
//llist_destroy(list);
return 0;
}
|
|