算法的复杂度为O(n)的迭代方法
和递归方法
typedef struct Node{
int data;
struct Node* next;
}Node;
#define LIST_LEN 10
Node * List = NULL;
//迭代方式
void reverse_ite(Node * list)
{
Node * old_head = NULL;
Node * new_head = NULL;
Node * cur = list;
while(cur != NULL)
{
old_head = cur->next;
cur->next = new_head;
new_head = cur;
cur = old_head;
}
List = new_head;
}
//递归方式
void reverse_recursive(Node * old_head, Node * new_head)
{
if(old_head == NULL)
{
List = new_head;
return;
}
Node * tmp = old_head->next;
old_head->next = new_head;
reverse_recursive(tmp, old_head);
}
void make_list(){
List = (Node *)malloc(sizeof(Node) * LIST_LEN);
int i = 0;
for(i = 0; i < (LIST_LEN - 1); i++)
{
(List + i)->data = i + 1;
(List + i)->next = List + i + 1;
}
(List + LIST_LEN - 1)->data = LIST_LEN;
(List + LIST_LEN - 1)->next = NULL;
}
void print_list()
{
Node * cur = List;
while(cur!=NULL){
printf("%d ", cur->data);
cur = cur->next;
}
printf("\n");
}
int main(int argc, char* argv[])
{
make_list();
print_list();
// reverse_ite(List); //迭代方式
reverse_recursive(List, NULL); //递归方式
print_list();
Sleep(3000);
return 0;
}