forked from DengWangBao/Leetcode-Java
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathReverseLinkedList.java
More file actions
30 lines (26 loc) · 715 Bytes
/
ReverseLinkedList.java
File metadata and controls
30 lines (26 loc) · 715 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
/**
* https://leetcode.com/articles/reverse-linked-list/
*/
public class ReverseLinkedList {
public ListNode reverseList(ListNode head) {
if (head == null || head.next == null) {
return head;
}
ListNode next = head.next;
ListNode newHead = reverseList(next);
next.next = head;
head.next = null;
return newHead;
}
// 耗时0ms
public ListNode reverseList2(ListNode head) {
ListNode dummy = new ListNode(0);
for (ListNode p = head; p != null; ) {
ListNode next = p.next;
p.next = dummy.next;
dummy.next = p;
p = next;
}
return dummy.next;
}
}