链表--02-链表逆序a[简单]

部分图片参考小象学院

剑指 Offer 24. 反转链表

https://leetcode-cn.com/problems/fan-zhuan-lian-biao-lcof

https://leetcode-cn.com/problems/reverse-linked-list/

题目:

已知链表头节点指针head,将链表逆序。(不可申请额外的空间)

示例:

输入: 1->2->3->4->5->NULL

输出: 5->4->3->2->1->NULL

限制:

0 <= 节点个数 <= 5000

思路:

依次遍历链表节点,没遍历一个节点就逆置一个节点。

具体做法:

 

#include <iostream>
using namespace std;

struct ListNode {
	int val;
	ListNode *next;
	ListNode(int x) : val(x), next(NULL) {}
};
 /********** 填写区 ***********/
class Solution {
public:
	ListNode* reverseList(ListNode* head) {
		/********** 填写区 ***********/
		ListNode* new_head = NULL;  //创建新头指针
		while (head)
		{
			ListNode* temp = head->next; //1.备份head->next
			head->next = new_head;   //2.将head->next指向new_head
			new_head = head;     //3.1 移动new_head
			head = temp;         //3.2 移动head
		}
		return new_head;
		/********** 填写结束 *********/
	}
};

void showList(ListNode* head)  //遍历
{
	while (head)  
	{
		cout << head->val << endl;
		head = head->next;
	}
}

void test01()
{
	ListNode a(1);  //创建数据用于测试
	ListNode b(2);
	ListNode c(3);
	ListNode d(4);
	ListNode e(5);
	a.next = &b;
	b.next = &c;
	c.next = &d;
	d.next = &e;
	e.next = NULL;
	ListNode* head = &a; //头指针
	cout << "Before reverse: " << endl;
	showList(head);  //遍历

	cout << "After reverse: " << endl;
	Solution s;
	head = s.reverseList(&a); //传入参数进行逆序
	showList(head);  //遍历
}

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值