206. Reverse Linked List
Problem:
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?
思路:
保存一个prev指针和next指针,分别指向head的前一个和后一个结点,只需让head重新指向prev即可。
Solution (C++):
ListNode* reverseList(ListNode* head) {
using L = ListNode*;
L prev = NULL, next = NULL;
while (head) {
next = head->next;
head->next = prev;
prev = head;
head = next;
}
return prev;
}
性能:
Runtime: 8 ms Memory Usage: 7.7 MB
思路:
Solution (C++):
性能:
Runtime: ms Memory Usage: MB
思路:
Solution (C++):
性能:
Runtime: ms Memory Usage: MB
相关链接如下:
知乎:littledy
GitHub主页:https://github.com/littledy
github.io:https://littledy.github.io/
欢迎关注个人微信公众号:小邓杂谈,扫描下方二维码即可
作者:littledy
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文链接,否则保留追究法律责任的权利。