反转链表--力扣题

Posted 穿迷彩服的鲨鱼

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了反转链表--力扣题相关的知识,希望对你有一定的参考价值。


前言

给你单链表的头节点 head ,请你反转链表,并返回反转后的链表。


一、示例

示例 1:
在这里插入图片描述
输入:head = [1,2,3,4,5]
输出:[5,4,3,2,1]

示例 2:
在这里插入图片描述
输入:head = [1,2]
输出:[2,1]

示例 3:
输入:head = []
输出:[]

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/reverse-linked-list

二、解题代码

1.反转链表

代码如下(示例):

/// <summary>
/// 反转链表
/// </summary>
/// <param name="head"></param>
/// <returns></returns>
ListNode* reverseList(ListNode* head)
{
	ListNode* newhead = NULL;
	ListNode* Next = NULL;
	while (head)
	{
		Next = head->next;
		head->next = newhead;
		newhead = head;
		head = Next;
	}
	return newhead;
}

2.测试代码

代码如下(示例):

#include<iostream>
using namespace std;

struct ListNode
{
	int val;
	ListNode* next;
	ListNode() :val(), next(NULL) {}
};
/// <summary>
/// 测试代码,创建链表
/// </summary>
/// <param name="head"></param>
/// <param name="n"></param>
void CreateListNode(ListNode* head, int n)
{
	ListNode* p = head;
	for (int i = 1; i <= n; i++)//创建链表并输入0--n
	{
		ListNode* pNew = new ListNode();
		pNew->val = i;
		pNew->next = NULL;
		p->next = pNew;
		p = pNew;
	}
}
/// <summary>
/// 测试代码,遍历链表查看数据
/// </summary>
/// <param name="head"></param>
/// <param name="n"></param>
void TraverseListNode(ListNode* head)
{
	ListNode *p = head;
	while (p != NULL)
	{
		cout << p->val << " ";
		p = p->next;
	}
}
/// <summary>
/// 反转链表
/// </summary>
/// <param name="head"></param>
/// <returns></returns>
ListNode* reverseList(ListNode* head)
{
	ListNode* newhead = NULL;
	ListNode* Next = NULL;
	while (head)
	{
		Next = head->next;
		head->next = newhead;
		newhead = head;
		head = Next;
	}
	return newhead;
}
/// <summary>
/// 测试代码
/// </summary>
/// <returns></returns>
int main()
{
	ListNode* head = NULL;
	ListNode* newHead = NULL;
	head = new ListNode();
	int n = 5;
	CreateListNode(head,n);
	TraverseListNode(head);

	cout << endl;
	newHead = reverseList(head);
	TraverseListNode(newHead);

	//cout << head->val << endl;

	return 0;
}

3.结果

在这里插入图片描述


总结

在这里插入图片描述

以上是关于反转链表--力扣题的主要内容,如果未能解决你的问题,请参考以下文章

1024狂欢力扣经典链表OJ题合集

链表

精选力扣500题 第1题 LeetCode 206. 反转链表 c++详细题解

精选力扣500题 第14题 LeetCode 92. 反转链表 IIc++详细题解

力扣题库--704. 二分查找

刷了力扣题之后,我也变的一发不可收拾了?