Skip to content

add solution and test case for 1721 #146

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 5 commits into from
Jan 11, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
38 changes: 38 additions & 0 deletions src/main/java/com/fishercoder/solutions/_1721.java
Original file line number Diff line number Diff line change
Expand Up @@ -30,4 +30,42 @@ public ListNode swapNodes(ListNode head, int k) {
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 = 0;
int secondIndex = 0;
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
ListNode node = new ListNode(nums[i]);
current.next = node;
current = current.next;
}
return dummy.next;
}
}
}
38 changes: 38 additions & 0 deletions src/test/java/com/fishercoder/_1721Test.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
package com.fishercoder;

import com.fishercoder.common.classes.ListNode;
import com.fishercoder.solutions._1721;
import org.junit.BeforeClass;
import org.junit.Test;

import static org.junit.Assert.assertEquals;

public class _1721Test {
private static _1721.Solution2 solution2;
private static ListNode expected;
private static ListNode node;
private static int k;

@BeforeClass
public static void setup() {
solution2 = new _1721.Solution2();
}

@Test
public void test1() {
node = new ListNode(1);
node.next = new ListNode(2);
node.next.next = new ListNode(3);
node.next.next.next = new ListNode(4);
node.next.next.next.next = new ListNode(5);

expected = new ListNode(1);
expected.next = new ListNode(4);
expected.next.next = new ListNode(3);
expected.next.next.next = new ListNode(2);
expected.next.next.next.next = new ListNode(5);

k = 2;
assertEquals(expected, solution2.swapNodes(node, k));
}
}