forked from fishercoder1534/Leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path_1721.java
72 lines (66 loc) · 2.12 KB
/
_1721.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
64
65
66
67
68
69
70
71
72
package com.fishercoder.solutions;
import com.fishercoder.common.classes.ListNode;
import java.util.ArrayList;
import java.util.List;
public class _1721 {
public static class Solution1 {
public ListNode swapNodes(ListNode head, int k) {
List<Integer> list = new ArrayList<>();
ListNode tmp = head;
while (tmp != null) {
list.add(tmp.val);
tmp = tmp.next;
}
int first = list.get(k - 1);
int size = list.size();
int second = list.get(size - k);
list.remove(k - 1);
list.add(k - 1, second);
list.remove(size - k);
list.add(size - k, first);
ListNode pre = new ListNode(-1);
tmp = pre;
for (int i = 0; i < list.size(); i++) {
pre.next = new ListNode(list.get(i));
pre = pre.next;
}
return tmp.next;
}
}
public static class Solution2 {
public ListNode swapNodes(ListNode head, int k) {
if (head == null || head.next == null) {
return head;
}
// find length of list
int n = 0;
ListNode current = head;
while (current != null) {
current = current.next;
n++;
}
int[] nums = new int[n];
current = head;
int i = 0;
while (current != null) {
nums[i++] = current.val;
current = current.next;
}
int firstIndex;
int secondIndex;
firstIndex = k;
secondIndex = n - k;
int temp = nums[firstIndex - 1];
nums[firstIndex - 1] = nums[secondIndex];
nums[secondIndex] = temp;
ListNode dummy = new ListNode(-1);
current = dummy;
for (i = 0; i < n; i++) {
ListNode node = new ListNode(nums[i]);
current.next = node;
current = current.next;
}
return dummy.next;
}
}
}