-
Notifications
You must be signed in to change notification settings - Fork 31
/
1721.java
42 lines (39 loc) · 1.03 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
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode swapNodes(ListNode head, int k) {
if(head.next == null){
return head;
}
ListNode current = head, first = head, second = head;
int i = 1;
while(current != null){
if(i == k){
first = current;
}
i++;
current = current.next;
}
int j = 1;
current = head;
while(current != null){
if(j == i-k){
int temp = current.val;
current.val = first.val;
first.val = temp;
break;
}
current = current.next;
j++;
}
return head;
}
}