单链表转置都很熟里,这里只是练一下链表操作,另外还有几点需要注意,如果是递归解决该问题呢,如果是相邻两个转置有怎么处理。
1. 单链表转置非递归
void reverse(struct Node **list)
{
struct Node *currentp = *list;
struct Node *pleft = NULL;
struct Node *pright = NULL;
while (currentp != NULL) {
pright = currentp->next;
currentp->next = pleft;
pleft = currentp;
currentp = pright;
}
*list = pleft;
}
2. 单链表转置递归
struct Node* recursive_reverse(struct Node *list)
{
struct Node *head = list;
struct Node *p = r_reverse(list);
head->next = NULL;
return p;
}
struct Node *r_reverse(struct Node *list)
{
if (NULL == list || NULL == list->next)
return list;
struct Node *p = r_reverse(list->next);
list->next->next = list;
return p;
}
3. 单链表相邻元素转置(非递归)
struct Node* recursive_reverse(struct Node *list)
{
struct Node *head = list;
struct Node *p = r_reverse(list);
head->next = NULL;
return p;
}
struct Node *r_reverse(struct Node *list)
{
if (NULL == list || NULL == list->next)
return list;
struct Node *p = r_reverse(list->next);
list->next->next = list;
return p;
}
4 单链表相邻元素转置(递归)
struct Node * recursive_partial_reverse(struct Node *list)
{
if (NULL == list || NULL == list->next)
return list;
struct Node *p = list->next;
struct Node *node = recursive_partial_reverse(list->next->next);
list->next->next = list;
list->next = node;
return p;
}