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…
Reference in new issue