使用迭代法(头插入法)和递归法实现单链表的逆序 c++实现

1.使用迭代法实现单链表逆序(头插入法)

#include "stdafx.h"
#include
#include"stdlib.h"
#include
#include
#include
#include
using namespace std;
struct Item
{
	char c;
	Item *next;
};
Item* Routinel(Item *x)
{
	Item* prev = NULL, *curr = x;
	while (curr)
	{
		Item *next = curr->next;
		curr->next = prev;
		prev = curr;
		curr = next;
	}
	return prev;
}
void Routine2(Item *x)
{
	Item *curr = x;
	while (curr)
	{
		cout << curr->c <<"->";
		curr = curr->next;
	}
	cout << endl;
}
void main()
{
	Item* x, e = { 'e',NULL },d = { 'd',&e },  c = { 'c',&d },  b = { 'b',&c },a = { 'a',&b};
	x = Routinel(&a);
	Routine2(x);
	system("pause");
	//return 0;
}

2.使用递归法实现单链表的逆序

typedef struct node LinkNode;
struct node
{
	char data;
	LinkNode *next;
};
//返回新链表头节点
LinkNode* reverse_link_recursive(LinkNode *head)
{
	if (head == NULL)
		return NULL;
	LinkNode* reverse_head, *temp, *curr;
	if (head->next == NULL)
		return head;
	else
	{
		curr = head;
		temp = head->next;
		reverse_head = reverse_link_recursive(temp);
		temp->next = curr;
		curr->next = NULL;
	}
	return reverse_head;
}
void Routine2(LinkNode *x)
{
	LinkNode *curr = x;
	while (curr)
	{
		cout << curr->data<< "->";
		curr = curr->next;
	}
	cout << endl;
}
void main()
{
	LinkNode* x, e = { 'e',NULL }, d = { 'd',&e }, c = { 'c',&d }, b = { 'b',&c }, a = { 'a',&b };
	x = reverse_link_recursive(&a);
	Routine2(x);
	system("pause");
}

你可能感兴趣的:(c++语言,算法与数据结构,c语言)