#include <stdio.h>
#include <malloc.h>
typedef struct node
{
int value;
struct node *next;
}Listnode;
Listnode* CreateList(Listnode *head)//建立链表
{
if(head == NULL)
return NULL;
head = (Listnode*)malloc(sizeof(Listnode));
head->value = 1;
head->next = NULL;
int i;
Listnode *p = head;
Listnode *q;
for(i=2;i<10;i++)
{
q = (Listnode*)malloc(sizeof(Listnode));
q->value = i;
p->next = q;
q->next = NULL;
p = q;
}
printf("链表节点为:\n");
p = head;
while(p)
{
printf("%d\t",p->value);
p = p->next;
}
printf("\n");
return head;
}
Listnode * ReverseList(Listnode* head)//迭代法
{
if(head == NULL)
return NULL;
Listnode *prve, *current,*temp;
current = head;
prve = NULL;
while(current->next)
{
temp = current->next;
current->next = prve;
prve = current;
current = temp;
}
current->next = prve;
return current;
}
Listnode *ReverseList_recursive(Listnode *head)//递归法
{
if(head == NULL)
return NULL;
Listnode *temp,*current,*head_reverselist;
if(head->next == NULL)
return head;
else
{
current = head;
temp = current->next;
head_reverselist = ReverseList_recursive(temp);//返回最后一个节点,也就是反转后的头结点
temp->next = current;
current->next = NULL;
}
return head_reverselist;
}
void PrintList(Listnode *head)
{
if(head == NULL)
return;
printf("反转后的链表节点为:\n");
while(head)
{
printf("%d\t",head->value);
head = head->next;
}
printf("\n");
}
int main()
{
Listnode *head;
head = CreateList(head);
head = ReverseList(head);//反转一次
printf("迭代方法:\n");
PrintList(head);
head = ReverseList_recursive(head);//反转第二次,恢复原状
printf("递归方法:\n");
PrintList(head);
return 0;
}
结果: