/******************************************************************************************
* main.c
* Created on: 24-Jan-2018 20:25:28
* Original author: linx
* Computer Science & Technology, Linx
* Copyright (c) 2018-2020. All rights reserved.
******************************************************************************************/
#include <stdio.h>
#include <stdlib.h>
typedef int datatype;
typedef struct node_t {
datatype value;
struct node_t *next;
} node, *link;
static const int kLIST_CNT = 5;
int add_node(link *head, datatype data);
void reverse_link(link *head);
/*void reverse_link_1(link *head);*/
link reverse_link_ret(link head);
link reverse_recursive(link head);
void traverse_link(link head);
void release_link(link *head);
int runtest();
int main() {
runtest();
return 0;
}
int runtest() {
link head = NULL;
int loop = kLIST_CNT;
while (loop > 0)
add_node(&head, loop--);
traverse_link(head);
reverse_link(&head);
traverse_link(head);
link relnk = reverse_link_ret(head);
traverse_link(relnk);
link recursive = reverse_recursive(relnk);
traverse_link(recursive);
release_link(&recursive);
return 0;
}
int add_node(link *head, datatype data) {
link newnode = (link)malloc(sizeof(*newnode));
if (NULL == newnode) {
return -1;
}
newnode->value = data;
newnode->next = *head;
*head = newnode;
return 0;
}
/*
void reverse_link_1(link *head) {
printf("%s\n", __FUNCTION__);
if (NULL == *head)
return;
link head_node = *head;
link current_node = (*head)->next;
head_node->next = NULL;
while (current_node) {
link next_node = current_node->next;
current_node->next = head_node;
head_node = current_node;
*head = current_node;
current_node = next_node;
}
}
*/
void reverse_link(link *head) {
printf("%s\n", __FUNCTION__);
link prev = NULL;
link current = *head;
link next = NULL;
while (NULL != current) {
next = current->next;
current->next = prev;
prev = current;
current = next;
}
*head = prev;
}
link reverse_link_ret(link current) {
printf("%s\n", __FUNCTION__);
link prev = NULL;
link next = NULL;
while (NULL != current) {
next = current->next;
current->next = prev;
prev = current;
current = next;
}
return prev;
}
link reverse_recursive(link head) {
printf("%s\n", __FUNCTION__);
if (NULL == head || NULL == head->next)
return head;
link tmp = reverse_recursive(head->next);
head->next->next = head;
head->next = NULL;
return tmp;
}
void traverse_link(link head) {
printf("%s\n", __FUNCTION__);
while (NULL != head) {
printf("%d->%s", head->value, head->next ? "": "NULL\n");
head = head->next;
}
printf("\n");
}
void release_link(link *head) {
printf("%s\n", __FUNCTION__);
while (NULL != *head) {
link tmp = *head;
printf("%d->%s", tmp->value, tmp->next ? "": "NULL\n");
*head = (*head)->next;
free(tmp);
tmp = NULL;
}
}