头结点有数据的单链表
方法1:
LinkList reverse_list(LinkList list)
{
LinkedNode *pre = list;
LinkedNode *cur = list->next;
LinkedNode *next = NULL;
if(list == NULL || list->next == NULL)
return;
/*在这里实现翻转*/
while(cur != NULL)
{
next = cur->next;
cur->next = pre;
pre = cur;
cur = next;
}
list->next = NULL;
list = pre;
return list;
}
方法2:递归
void reverse_the_list(LinkedNode *cur, LinkList *list)
{
LinkedNode *next = NULL;
if(cur == NULL || cur->next == NULL)
{
*list = cur;
}
else
{
next = cur->next;
reverse_the_list(next, list);
next->next = cur;
cur->next = NULL;
}
return;
}
完整代码:
#include <stdio.h>
#include <malloc.h>
typedef int DataType;
typedef struct node
{
DataType data;
struct node *next;
}LinkedNode, *LinkList;
LinkList create_list()
{
DataType value[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
int len = sizeof(value) / sizeof(DataType);
int i = 0;
LinkedNode *list_head = NULL;
LinkedNode *temp = NULL;
LinkedNode *p = NULL;
list_head = (LinkedNode*)malloc(sizeof(LinkedNode));
list_head->data = value[0];
list_head->next = NULL;
temp = list_head;
for(i = 1; i < len; i++)
{
while (temp->next != NULL)
{
temp = temp->next;
}
p = (LinkedNode*)malloc(sizeof(LinkedNode));
p->data = value[i];
p->next = NULL;
temp->next = p;
}
return list_head;
}
void print(LinkList list)
{
LinkedNode *temp = NULL;
if(list == NULL)
return;
temp = list;
while(temp != NULL)
{
printf("%d ", temp->data);
temp = temp->next;
}
printf("\n");
return;
}
LinkList reverse_list(LinkList list)
{
LinkedNode *pre = list;
LinkedNode *cur = list->next;
LinkedNode *next = NULL;
if(list == NULL || list->next == NULL)
return;
/*在这里实现翻转*/
while(cur != NULL)
{
next = cur->next;
cur->next = pre;
pre = cur;
cur = next;
}
list->next = NULL;
list = pre;
return list;
}
void reverse_the_list(LinkedNode *cur, LinkList *list)
{
LinkedNode *next = NULL;
if(cur == NULL || cur->next == NULL)
{
*list = cur;
}
else
{
next = cur->next;
reverse_the_list(next, list);
next->next = cur;
cur->next = NULL;
}
return;
}
int main()
{
LinkList list = NULL;
LinkedNode *temp = NULL;
LinkedNode *temp1 = NULL;
list = create_list();
print(list);
printf("after first reverse:the node is:\n");
temp=reverse_list(list);
print(temp);
temp1 = temp;
reverse_the_list(temp1, &temp);
printf("after second reverse:the node is:\n");
print(temp);
return 0;
}
实验结果: