要求将一带链表头List head的单向链表逆序。
#include<stdio.h>
typedef struct _list_node{
struct _list_node *next;
int data;
}list_node;
void print_list(list_node *head)
{
head = head->next;
while(head)
{
printf("%d ", head->data);
head = head->next;
}
printf("\n");
}
list_node *reverse_list(list_node *head)
{
list_node *h = head->next;
list_node *new_head = head;
list_node *tail = NULL;
while(h)
{
head = h->next;
h->next = tail;
tail = h;
h = head;
}
new_head->next = tail;
return new_head;
}
list_node *_reverse_list_recu(list_node *new_head, list_node *head)
{
if (head->next == NULL) {
new_head->next = head;
return head;
}
list_node *t = _reverse_list_recu(new_head, head->next);
t->next = head;
return head;
}
list_node *reverse_list_recu(list_node *head)
{
list_node *t = _reverse_list_recu(head, head->next);
t->next = NULL;
return head;
}
int main(int argc, char *argv[])
{
int i;
list_node *head, *t, *tail;
head = (list_node *)malloc(sizeof(list_node));
tail = head;
for (i = 0; i < 10; i++)
{
t = (list_node *)malloc(sizeof(list_node));
t->data = i;
t->next = NULL;
tail->next = t;
tail = t;
}
print_list(head);
reverse_list(head);
print_list(head);
reverse_list_recu(head);
print_list(head);
return 0;
}