逆置/反转单链表

30 篇文章 2 订阅

思路:摘结点法



//逆置/反转单链表
#include<iostream>
using namespace std;

typedef int DataType;
typedef struct SListNode
{
	DataType data;            //数据
	struct SListNode * next;   //指向下一个结点的指针
}SListNode;

SListNode* CreateNode(DataType x)  //创造结点
{
	//1.先开辟空间 2.数据赋给data 3.指针置空
	SListNode* NewNode = (SListNode *)malloc(sizeof (SListNode));
	NewNode->data = x;
	NewNode->next = NULL;

	return NewNode;
}

void PushBack(SListNode * &ppHead, DataType Data)
{
	//1.none 2.one and more
	if (ppHead == NULL)
	{
		ppHead = CreateNode(Data);
	}
	else
	{
		//1.先找到尾结点 2.把新节点链起来
		SListNode* cur = ppHead;
		while (cur->next)
		{
			cur = cur->next;
		}
		cur->next = CreateNode(Data);

	}
}
//打印
void PrintSNodeList(SListNode *&ppHead)
{
	while (ppHead)
	{
		printf("%d->", ppHead->data);
		ppHead = ppHead->next;
	}
	cout << "NULL" << endl;
}

//逆置/反转单链表
SListNode* ReverseList(SListNode*& pHead)
{
	//摘结点法
	SListNode* cur = pHead;  
	SListNode* newHead = NULL;  //创建一个新头结点
	while (cur)
	{
		SListNode* tmp = cur;  //tmp指向cur
		cur = cur->next;		//cur指向下一个
		tmp->next = newHead;    //1.第一次tmp->next=NULL 2.以后每次利用tmp把结点和newHead连起来
		newHead = tmp;   //再把头结点向前移
	}
	return newHead;

}
void Test()
{
	SListNode* pHead = NULL;
	PushBack(pHead, 1);
	PushBack(pHead, 2);
	PushBack(pHead, 3);
	PushBack(pHead, 4);
	PushBack(pHead, 5);
	PushBack(pHead, 6);
	PushBack(pHead, 7);
	PushBack(pHead, 8);
	SListNode* newHead=ReverseList(pHead);
	PrintSNodeList(newHead);
}

int main()
{
	Test();
	system("pause");
	return 0;
}




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值