-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path206.反转链表.java
63 lines (54 loc) · 1.31 KB
/
206.反转链表.java
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
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
import java.util.ArrayList;
/*
* @lc app=leetcode.cn id=206 lang=java
*
* [206] 反转链表
*/
// Definition for singly-linked list.
class ListNode {
int val;
ListNode next;
ListNode() {
}
ListNode(int val) {
this.val = val;
}
ListNode(int val, ListNode next) {
this.val = val;
this.next = next;
}
}
// @lc code=start
class Solution {
public Integer[] convertLinked(ListNode node) {
ArrayList<Integer> list = new ArrayList<>();
while (node != null) {
list.add(node.val);
node = node.next;
}
return list.toArray(Integer[]::new);
}
public ListNode convertArr(Integer[] arr) {
ListNode head = new ListNode(), node = head;
for (Integer i : arr) {
node.next = new ListNode(i);
node = node.next;
}
return head.next;
}
public Integer[] reverse(Integer[] arr) {
int left = 0, right = arr.length - 1;
while (left < right) {
Integer tmp = arr[left];
arr[left] = arr[right];
arr[right] = tmp;
left++;
right--;
}
return arr;
}
public ListNode reverseList(ListNode head) {
return convertArr(reverse(convertLinked(head)));
}
}
// @lc code=end