反转链表

#include <iostream>
using namespace std;

typedef struct List 
{
	int value;
	struct List *next;
}list,*ListNode;

//反转
list *reverse(ListNode head)
{
	//如果链表为空,反转还是空链表;如果链表里面只有一个元素,反转还是自身,所以直接返回。
	if (head==NULL || head->next==NULL)
	{
		return head;
	}
	ListNode pre=head,cur=head->next;
	pre->next=NULL;
	while(cur!=NULL)
	{
		list *nxt=cur->next;
		cur->next=pre;
		pre=cur;
		cur=nxt;
	}
	return pre;
}
//递归
list *reverse2(ListNode head)
{
	if (head==NULL || head->next==NULL)
	{
		return head;
	}
	else
	{
		list *newhead=reverse2(head->next);
		head->next->next=head;
		head->next=NULL;
		return newhead;
	}
}
//打印
void printlist(ListNode lianbiao)
{
	while(lianbiao!=NULL)
	{
		cout<<lianbiao->value<<" ";
		lianbiao=lianbiao->next;
	}
}
//头插法建立链表
void headinsert(ListNode &LB,int i)
{
	list *p=(list*)malloc(sizeof(list));
	p->value=i;
	p->next=NULL;
	if (LB==NULL)
	{
		LB=p;
	}
	else
	{
		p->next=LB;
		LB=p;
	}
}
```cpp
//尾插法建立链表
void tailinsert(list *&newlianbiao,int n,list *pold)
{
	for (int i=0;i<n;i++)
	{
		List *pnew=(list*)malloc(sizeof(List));
		pnew->value=i;
		pnew->next=NULL;
		if (newlianbiao==NULL)
		{
			newlianbiao=pnew;
			pold=newlianbiao;
		}
		else
		{
			pold->next=pnew;
			pold=pnew;
		}
	}
}
void main()
{
	List *newlianbiao=NULL,	*pold=NULL;
	for (int i=0;i<9;i++)
		{
			List *pnew=(list*)malloc(sizeof(List));
			pnew->value=i;
			pnew->next=NULL;
			if (newlianbiao==NULL)
			{
				newlianbiao=pnew;
				pold=newlianbiao;
			}
			else
			{
				pold->next=pnew;
				pold=pnew;
			}
	}
	printlist(newlianbiao);
	list *reverselianbiao=reverse2(newlianbiao);
	printlist(reverselianbiao);
}

https://blog.csdn.net/geekmanong/article/details/51097196
https://blog.csdn.net/fx677588/article/details/72357389
https://blog.csdn.net/qq_42351880/article/details/88637387
https://blog.csdn.net/u014398524/article/details/104127722
https://www.cnblogs.com/xiaokang01/p/12409914.html(单链表的建立)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值