1. 算法
#include <stdio.h>
struct LinkNode {
int data;
struct LinkNode *next;
};
struct LinkNode * reverseLinkList(struct LinkNode *L) {
struct LinkNode *r = NULL, *s; // r为逆置后链表的头指针
while (L) {
s = L->next;
L->next = r;
r = L;
L = s;
}
return r;
}
struct LinkNode * createLinkList() {
int data;
int flag = 0;
struct LinkNode *L, *p, *q;
printf("input your data:");
while(scanf("%d", &data) != EOF) {
q = (struct LinkNode *)malloc(sizeof(struct LinkNode));
q->data = data;
if (flag == 0) {
L = q;
p = L;
flag = 1;
}
else {
p->next = q;
p = q;
}
printf("input your data:");
}
p->next = NULL;
return L;
}
void printLinkList(struct LinkNode *L) {
struct LinkNode *s = L;
while (s) {
printf("%d\n", s->data);
s = s->next;
}
}
void printAndDestroyLinkList(struct LinkNode *L) {
struct LinkNode *r;
while (L) {
r = L->next;
printf("%d\n", L->data);
printf("地址%d\n", L);
free(L);
printf("销毁了一个结点\n");
L = r;
}
}
int main() {
struct LinkNode *testLinkList;
testLinkList = createLinkList();
printf("逆置前:\n");
printLinkList(testLinkList);
testLinkList = reverseLinkList(testLinkList);
printf("逆置后:\n");
printAndDestroyLinkList(testLinkList);
return 0;
}
2. 运行
3. 说明
(1)C语言代码描述;
(2)非递归实现,容易理解。