#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct ListNode{
char value;
struct ListNode * next;
}ListNode;
//单链表倒置——头插法
ListNode * listReverse(ListNode * head){
if(NULL == head){
return NULL;
}
if(NULL == head->next){
return head;
}
ListNode * p = head->next;
head->next = NULL;
ListNode * tmp;
while(p){
tmp = p->next;
p->next = head->next;
head->next = p;
p = tmp;
}
return head;
}
//创建单链表
ListNode * makeList(char * src, ListNode *head){
if(NULL == src){
return NULL;
}
//创建头结点
head = (ListNode *) malloc(sizeof(ListNode));
head->next = NULL;
ListNode *p = head;
while(*src != '\0'){
ListNode * node = (ListNode *) malloc(sizeof(ListNode));
if(NULL == node){
return NULL;
}
p->next = node;
p = p->next;
p->value = *src;
p->next = NULL;
src++;
}
return head;
}
int main(){
char *src = "abcde";
ListNode * head, *tmp;
head = makeList(src, head);
tmp = head;
do{
tmp = tmp->next;
printf("######%c\n", tmp->value);
}while(tmp->next);
head = listReverse(head);
tmp = head;
do{
tmp = tmp->next;
printf("******%c\n", tmp->value);
}while(tmp->next);
free(head);//释放malloc分配的堆空间
head = NULL;//释放后,将指针置为NULL,防止后面的程序误用
}