链表逆置递归

#include <iostream>
using namespace std;


typedef int ElemType;
typedef struct _Node
{
	ElemType data;
	struct _Node *next;
}Node;


Node* initNode()
{
	Node *ptr = (Node *)malloc(sizeof(struct _Node));
	if (ptr != NULL)
	{
		memset(ptr, 0, sizeof(Node));
		return ptr;
	}
	else 
		return NULL;
}

bool linkNode(Node* head, ElemType* start, ElemType* end, int num)
{
	if (head == NULL || end-start<0)
	{
		return false;
	}

	while(head->next != NULL)
	{
		head = head->next;
	}

	for(int i=0; i<num; ++i)
	{
		Node *tp = initNode();
		tp->data = *start;
		++start;
		head->next = tp;
		head = tp;
	}
	return true;
}

void Print(Node *head)
{
	if (head != NULL)
	{
		cout<<head->data<<" ";
		Print(head->next);
	}
}
void print_list(Node *head)
{
	if (head == NULL || head->next == NULL)
	{
		return ;
	}
	Print(head->next);
}

Node* re_list(Node *node, Node *next)
{
	if (node->next != NULL)
	{
		Node *head = re_list(node->next, next->next);
		next->next = node;
		node->next = NULL;
		return head;
	}
	else
	{
		return node;
	}
}

void resever_list(Node *head)//
{
	if (head == NULL || head->next == NULL)
	{
		return ;
	}
	Node *tmp = re_list(head->next, head->next->next);
	head->next = tmp;
}

int main()
{
	ElemType tp[] = {1,4,5,6,7,8,9};
	Node *head = initNode();
	linkNode(head, tp, tp+sizeof(tp),sizeof(tp)/sizeof(tp[0]));
	resever_list(head);
	print_list(head);
}

展开阅读全文

没有更多推荐了,返回首页