update q206

pull/10/head
yuanguangxin 4 years ago
parent 41578dbafd
commit 1ae42b25c1

@ -1,28 +1,19 @@
package .q206_.f1; package .q206_.f1;
import java.util.ArrayList;
import java.util.List;
/** /**
* o(n) * next o(n)
*/ */
class Solution { class Solution {
public ListNode reverseList(ListNode head) { public ListNode reverseList(ListNode head) {
if (head == null || head.next == null) { ListNode pre = null;
return head;
}
List<Integer> list = new ArrayList<>();
ListNode temp = head; ListNode temp = head;
while (temp != null) { while (temp != null) {
list.add(temp.val); ListNode t = temp.next;
temp = temp.next; temp.next = pre;
} pre = temp;
ListNode rs = new ListNode(list.get(list.size() - 1)); temp = t;
ListNode t1 = rs;
for (int i = list.size() - 2; i >= 0; i--) {
t1.next = new ListNode(list.get(i));
t1 = t1.next;
} }
return rs; return pre;
} }
} }

@ -1,18 +1,17 @@
package .q206_.f2; package .q206_.f2;
/** /**
* next o(n) * o(n)
*/ */
class Solution { class Solution {
public ListNode reverseList(ListNode head) { public ListNode reverseList(ListNode head) {
ListNode pre = null; if (head == null || head.next == null) {
ListNode temp = head; return head;
while (temp != null) {
ListNode t = temp.next;
temp.next = pre;
pre = temp;
temp = t;
} }
return pre; ListNode p = reverseList(head.next);
head.next.next = head;
head.next = null;
return p;
} }
} }

Loading…
Cancel
Save