从零开始的LC刷题(51): Reverse Linked List 链表就地逆置

本文介绍了如何从零开始解决LeetCode中的链表逆置问题,提供了两种方法:迭代首插法和递归逆置法。通过示例代码详细解析了每种方法的实现过程,并给出了运行时和内存使用情况。
摘要由CSDN通过智能技术生成

原题:

Reverse a singly linked list.

Example:

Input: 1->2->3->4->5->NULL
Output: 5->4->3->2->1->NULL

Follow up:

A linked list can be reversed either iteratively or recursively. Could you implement both?

有两种逆置方法,一种用的比较多是首插循环的方式,即设置一个头节点head2,使head2->next=nullptr,然后一直按首插法插入,例如:(h) (1->2->3->4)  ==>  (h->1) (2->3->4) ==>(h->2->1) (3->4)...

 结果:

Success

Runtime: 4 ms, faster than 99.70% of C++ online submissions forReverse Linked List.

Memory Usage: 9.1 MB, less than 59.47% of C++ online submissions for Reverse Linked List.

代码:

/**
 * Definition for singly-linked list.
 * struct ListNode 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值