- 论坛徽章:
- 0
|
#include <stdio.h>
#include <stdlib.h>
#define offsetof(type, field) ((long) &((type *)0)->field)
void freeList(void *link, long nextPos);
typedef struct List1 {
int data;
struct List1 *next;
} List1;
typedef struct List2 {
int data;
int data2;
struct List2 *next;
int data3;
} List2;
typedef struct Template {
int data;
} Template;
int main()
{
List1 a1, a2, a3;
List2 b1, b2;
List1 *headA = &a1;
List2 *headB = &b1;
a1.data = 1;
a1.next = &a2;
a2.data = 2;
a2.next = &a3;
a3.data = 3;
a3.next = NULL;
b1.data = b1.data2 = b1.data3 = 10;
b1.next = &b2;
b2.data = b2.data2 = b2.data3 = 15;
b2.next = NULL;
freeList((void *) headA, offsetof(List1, next));
freeList((void *) headB, offsetof(List2, next));
return 0;
}
void freeList(void *link, long nodePos)
{
void *nextNode;
if (link == NULL)
return ;
while (link)
{
/* make nextNode pointer point to next Node in the List */
nextNode = (void *) (*((char **) (link + nodePos)));
/* free(link); */
/* print first element in Node */
if (nextNode)
printf("%p::%d\n", (nextNode),
((Template *)nextNode)->data);
else
printf("%p::NULL\n", (nextNode));
link = nextNode;
}
}
|
这个代码很垃圾, 只是在上次你的基础上, 我扩展了, 只要一个链表的节点是一致的, 或者说, 只要该链表中next指针在结构体中的偏移是固定的(用宏offsetof计算), 就能正确进行遍历.
昨天讨论的指针问题, 也算给我平反了 ^^
更好的链表实现, 我见过的是postgresql中的, 不过具体比较复杂(我只潦草看了下). |
|