Skip to content
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

1721. Swapping Nodes in a Linked List #34

Merged
merged 1 commit into from
Jul 23, 2024
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
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
package com.xtenzq.leetcode;

import com.xtenzq.linkedlist.utils.ListNode;

public class ReverseBetween {

public static ListNode reverseBetween(ListNode head, int left, int right) {
if (head.next == null) {
return head;
}

ListNode curr = head, beforeList = null;
// traverse to the left - 1 node
for (int i = 0; i < left - 2; i++) {
curr = curr.next;
}

if (left > 1) {
beforeList = curr; // the node that will point to the reversed list
curr = curr.next; // traversal to the node to start reversing
}

int k = 0;
ListNode prev = null, nextNode = null, tail = null;
while (k < right - left + 1) {
if (k == 0) {
tail = curr; // save first node because it will become tail of the reversed list
}
// reverse node
nextNode = curr.next; // save next node
curr.next = prev; // reverse direction
prev = curr; // prev node is now current
curr = nextNode; // traversal
k++;
}

// if there are no nodes before the one we have to reverse
if (beforeList != null) {
beforeList.next = prev;
} else {
// if we reverse from the start
head = prev;
}

tail.next = nextNode;
return head;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
package com.xtenzq.leetcode;

import org.junit.jupiter.api.Test;

import static com.xtenzq.leetcode.ReverseBetween.reverseBetween;
import static com.xtenzq.linkedlist.utils.ListNode.buildLinkedList;
import static org.junit.jupiter.api.Assertions.assertEquals;

class ReverseBetweenTest {

@Test
void reverseBetween_case1() {
assertEquals(buildLinkedList(1, 4, 3, 2, 5), reverseBetween(buildLinkedList(1, 2, 3, 4, 5), 2, 4));
}

@Test
void reverseBetween_case2() {
assertEquals(buildLinkedList(5), reverseBetween(buildLinkedList(5), 1, 1));
}

@Test
void reverseBetween_case3() {
assertEquals(buildLinkedList(1, 2), reverseBetween(buildLinkedList(1, 2), 2, 2));
}

@Test
void reverseBetween_case4() {
assertEquals(buildLinkedList(2, 1), reverseBetween(buildLinkedList(1, 2), 1, 2));
}
}
Loading