可能有很多种实现方式,分享一下最朴实的方法。
首先是节点和Link List结构:
struct mynode { int value; mynode * next; };
struct mylist { mynode * first; mynode * last; };
提供一些基础函数:
void list_init(mylist * container) { container->first = 0; container->last = 0; }
bool list_isempty(mylist * container) { return 0 == container->first; }
mynode * list_first(mylist * container) { return container->first; }
mynode * list_next(mynode * node) { return node->next; }
void list_pushback(mylist * container, mynode * node) { if (list_isempty(container)) { container->first = node; container->last = node; } else { container->last->next = node; container->last = node; } node->next = 0; }
mynode * list_popfront(mylist * container) { mynode * frontpoint = container->first; container->first = frontpoint->next; return frontpoint; }
最关键的是反转Link List:
void list_reverse(mylist * container)
{ mynode * tempfirst = container->first;
mynode * templast = container->last;
if (tempfirst != templast) { container->last = tempfirst;
mynode * frontnode = container->first; mynode * nextnode = frontnode->next; while (nextnode != 0) { mynode * temp = nextnode->next; nextnode->next = frontnode; frontnode = nextnode; nextnode = temp; }
container->first = templast; container->last->next = 0; } }
主函数验证正常工作:
int _tmain(int argc, _TCHAR* argv[]) { mylist myinitiallist; list_init(&myinitiallist);
for (int t = 1; t <= 10; t++) { mynode * temp = (mynode *)malloc(sizeof(mynode)); temp->value = t; list_pushback(&myinitiallist, temp); }
mynode * a = list_first(&myinitiallist); while ( a) { printf("%d \n", a->value); a = list_next(a); }
list_reverse(&myinitiallist); mynode * b = list_first(&myinitiallist); while (b) { mynode * x = b; printf("%d \n", b->value); b = list_next(b); free(x); }
return 0; }