完整代码如下:
#include <stdio.h>
#include <malloc.h>
#include <windows.h>
#include <time.h>
#include <stdlib.h>
struct node {
int data;
struct node *next;
};
struct node *init_list(int num)
{
struct node *h = NULL, *t = NULL;
srand((unsigned)time(NULL));
while (num-- > 0) {
struct node *n = calloc(1, sizeof(struct node));
n->data = rand();
n->next = NULL;
if (!h) {
h = n;
t = n;
} else {
t->next = n;
t = n;
}
}
return h;
}
void deinit_list(struct node *head)
{
while (head) {
struct node *prev = head;
head = head->next;
free(prev); prev = NULL;
}
}
void print_list(struct node *head)
{
while (head) {
printf("%d ", head->data);
head = head->next;
}
printf("\n");
}
struct node *insert_list(struct node *head, struct node *n)
{
struct node *h = NULL;
if (head) {
if (n->data < head->data) {
h = n;
n->next = head;
} else {
struct node *prev = head;
h = head;
while (head = head->next) {
if (n->data < head->data) {
prev->next = n;
n->next = head;
return h;
}
prev = head;
}
prev->next = n;
n->next = NULL;
}
} else {
h = n;
n->next = NULL;
}
return h;
}
struct node *order_list(struct node *head)
{
struct node *h = NULL;
while (head) {
struct node *t = head;
head = head->next;
h = insert_list(h, t);
}
return h;
}
//这里用递归法来实现逆序,返回的是尾节点, pHEAD是指向链表头节点的指针的地址,用地址传递得到它,很重要
struct node *reverse_list_recursive(struct node *head, struct node **pHEAD)
{
struct node *t = head;
if (head = head->next) {
struct node *TAIL = reverse_list_recursive(head, pHEAD);
TAIL->next = t;
t->next = NULL;
return t;
} else {
*pHEAD = t;
return t;
}
}
//这里用交换指针的方法来实现,看起来更简单
//会写程序不难,难的是写出好的程序,哈哈
struct node *reverse_list(struct node *head)
{
struct node *prev = NULL;
while (head) {
struct node *next = head->next;
head->next = prev;
prev = head;
head = next;
}
return prev;
}
void main()
{
struct node *list = init_list(10);
print_list(list);
list = order_list(list);
print_list(list);
list = reverse_list(list);
print_list(list);
deinit_list(list);
}