链表例程:
typedef struct LISTNODE
{
void *data_p;
LISTNODE *next;
} mlistnode;
typedef struct MYLIST
{
int size;
mlistnode *head;
} mylist;
mylist *initial_mylist()
{
mylist *p = (mylist *)malloc(sizeof(mylist));
p->size = 0;
p->head = (mlistnode *)malloc(sizeof(mlistnode));
p->head->data_p = NULL;
p->head->next = NULL;
return p;
}
void freemylist(mylist *plist)
{
if (plist == NULL)
{
return;
}
mlistnode *pCurrent = plist->head; // 创建一个节点指针指向当前要删除的节点,这里是要删除head节点
mlistnode *pNext = NULL;
while (pCurrent != NULL)
{
// mlistnode *pNext = pCurrent->next; // 再创建一个节点指针指向下一个要删除的节点
pNext = pCurrent->next;
free(pCurrent); // 删除当前节点
pCurrent = pNext; // 指向下一个要删除的节点
}
free(plist);
}
// 插入数据
void insertData(mylist *plist, void *pdata, int pos)
{
if (plist == NULL)
{
return;
}
if (pos < 0 && pos > plist->size)
{
return;
}
mlistnode *newNode = (mlistnode *)malloc(sizeof(mlistnode));
newNode->data_p = pdata;
newNode->next = NULL;
mlistnode *pCurrent = plist->head;
for (int i = 0; i < pos; i++)
{
pCurrent = pCurrent->next;
}
newNode->next = pCurrent->next;
pCurrent->next = newNode;
plist->size++;
}
// 打印链表
struct personlist
{
string name;
int age;
};
typedef void (*MYPRINT)(void *);
void myprint(void *datap)
{
personlist *p = (personlist *)datap;
cout << “名字是:” << p->name << " 年龄是:" << p->age << endl
<< endl;
};
void printmylist(mylist *listp, MYPRINT mprint)
{
if (listp == NULL)
{
return;
}
mlistnode *pCurrent = listp->head->next;
for (int i = 0; i < listp->size; i++)
{
mprint(pCurrent->data_p);
pCurrent = pCurrent->next;
}
}
void test08()
{
personlist p1 = {“AAA”, 21};
personlist p2 = {“BBB”, 22};
personlist p3 = {“CCC”, 23};
personlist p4 = {“DDD”, 24};
personlist p5 = {“EEE”, 25};
mylist *mlist = initial_mylist();
insertData(mlist, &p1, 0);
insertData(mlist, &p2, 0);
insertData(mlist, &p3, 0);
insertData(mlist, &p4, 0);
insertData(mlist, &p5, 0);
printmylist(mlist, myprint);
}
extern “C” void app_main(void)
{
test08();
}