内容简介:Reverse a singly linked list.Example:Follow up:
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?
反转单链表,看到我好几年前通过的代码居然是用List遍历保存之后再倒序遍历反转,然而还RE了好几次。。。往事突然浮现在脑海,没忍住又重写了一下。
耗时0ms
class Solution {
public ListNode reverseList(ListNode head) {
ListNode cur = head, prev = null, temp = null;
while (cur != null) {
temp = cur.next;
cur.next = prev;
prev = cur;
cur = temp;
}
return prev;
}
}
以前的代码是这样的(耗时464ms):
public class Solution {
public ListNode reverseList(ListNode head) {
if(head == null || head.next == null)
return head;
ArrayList<Integer> list = new ArrayList<Integer>();
ListNode p = head;
while(p!=null) {
list.add(p.val);
p = p.next;
}
ListNode q = head;
for(int i=list.size()-1; i>=0; i--) {
q.val = list.get(i);
q = q.next;
}
return head;
}
}
以上所述就是小编给大家介绍的《LeetCode - 206. Reverse Linked List》,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对 码农网 的支持!
猜你喜欢:- LeetCode - 206. Reverse Linked List
- 数据结构与算法 | Leetcode 206:Reverse Linked List
- Leetcode PHP题解--D78 206. Reverse Linked List
- LeetCode 之 JavaScript 解答第206题 —— 反转链表(Reverse Linked List)
本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们。
C++ 程序设计语言(特别版)(英文影印版)
[美] Bjarne Stroustrup / 高等教育出版社 / 2001-8-1 / 55.00
《C++程序设计语言》(特别版)(影印版)作者是C++的发明人,对C++语言有着全面、深入的理解,因此他强调应将语言作为设计与编程的工具,而不仅仅是语言本身,强调只有对语言功能有了深入了解之后才能真正掌握它。《C++程序设计语言》编写的目的就是帮助读者了解C++是如何支持编程技术的,使读者能从中获得新的理解,从而成为一名优秀的编程人员和设计人员。一起来看看 《C++ 程序设计语言(特别版)(英文影印版)》 这本书的介绍吧!