链表逆置

单链表逆置问题:

1头插法

2递归

具体过程大致图如下:


代码实现:

#include <iostream>
using namespace std;

typedef int elemtype;
typedef struct ListNode
{
	elemtype data;
	ListNode *next;
}ListNode,*List;
ListNode *Buynode()
{
	ListNode* p = (ListNode *)malloc(sizeof(ListNode));
	if (NULL == p)
		exit (-1);
	memset(p,0,sizeof(ListNode));
	p->next = NULL;
	return p;
}
ListNode *init_list()
{
	ListNode *p = Buynode();
	return p;
}

void push_front(ListNode *head,int value)
{
	if (head == NULL)
	{
		return;
	}
	ListNode*p = Buynode();
	p->data = value;
	p->next = head->next;
	head->next = p;

}

void print(ListNode *head)
{
	if (head == NULL)
		return ;
	ListNode *pcur = head->next;
	while (pcur != NULL)
	{
		cout<<pcur->data<<" ";
		pcur = pcur->next;
	}
	cout<<endl;
}
////////////链表逆置--头插法////////////////////
void rerverse(ListNode *head)
{
	if (head == NULL)
		return ;
	ListNode *p = head->next;
	ListNode *s = NULL;
	head->next = NULL;
	while (p!= NULL)//头插s,改变头结点的指向
	{
		s = p;
		p = p->next;
		s->next = head->next;
		head->next = s;
	}
}
////////////////////////链表逆置 (递归)//////////////////////////
ListNode *phead = NULL;//用来记录逆置之后新的第一个结点
void reverse2(ListNode *s,ListNode *p)
{
	if (p != NULL)
	{
		reverse2(p,p->next);
		p->next = s;//返回的时候指针反向
	}
	else
	{
		phead = s;//记录新的第一个结点
	}

}
void reverse1(ListNode *head)
{
	if (head == NULL)
		return;
	ListNode *p = head->next;//注意递归的起始条件
	ListNode *s = NULL;
	reverse2(s,p);
}
void main()
{
	List head;
	int ar[] = {12,23,34,45,56,67,78,89,90,100};
	int len = sizeof(ar)/sizeof(ar[0]);
	head= init_list();
	for (int i = 0;i<len;++i)
	{
		push_front(head,ar[i]);
	}
	print(head);
	reverse1(head);
	head->next = phead;
	print(head);

}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章