C语言实现单向链表的反转
作者:大宝同学
时间:2015-12-22
测试环境:VC++6.0 gcc version 4.6.3 (Ubuntu/Linaro 4.6.3-1ubuntu5)
/*
描述:将单向链表反转
作者:大宝同学
时间:2015-12-22
*/
#include <stdio.h>
#include <malloc.h>
struct list
{
struct list *p;
int n;
};
typedef struct list List;
/*
通过结构体List 创建一个链表
*/
List *create_list()
{
int i = 0;
List *head = NULL;
List *pnote = NULL;
pnote = (List *)malloc(sizeof(List));
head = pnote;
for(i=0; i<4; i++)
{
pnote->n = i + 1;
pnote->p = (List *)malloc(sizeof(List));
pnote = pnote->p;
}
pnote->n = i + 1;
pnote->p = NULL;
return head;
}
/*
释放链表空间
*/
void free_list(List **head)
{
List *pnote = *head;
while((*head)->p != NULL)
{
pnote = (*head)->p;
free(*head);
*head = pnote;
}
*head = NULL;
}
/*
打印链表
*/
void print_list(List *head)
{
if(head == NULL)
{
printf("head is NULL!\n");
return ;
}
do
{
printf("%d ", head->n);
head = head->p;
}
while(head != NULL);
printf("\n");
}
/*
将链表反转
*/
List *list_reverse(List *head)
{
List *new_head = NULL;
List *pnote = NULL;
if(head == NULL)
{
printf("head is NULL!\n");
return head;
}
new_head = head->p;
head->p = NULL;
do
{
pnote = new_head;
new_head = pnote->p;
pnote->p = head;
head = pnote;
}
while(new_head != NULL);
return pnote;
}
int main()
{
List *head = create_list();
print_list(head);
head = list_reverse(head);
print_list(head);
free_list(&head);
print_list(head);
printf("*** Debug test ***\n");
return 0;
}