use of com.fishercoder.common.classes.ListNode in project Leetcode by fishercoder1534.
the class _25 method reverseKGroup.
/**
*We use recursion to go all the way until the end: when the number of nodes are smaller than k;
* then we start to reverse each group of k nodes from the end towards the start.
*/
public ListNode reverseKGroup(ListNode head, int k) {
ListNode curr = head;
int count = 0;
while (curr != null && count != k) {
// find the k+1 node
curr = curr.next;
count++;
}
if (count == k) {
/**
*after this below recursive call finishes, it'll return head;
* then this returned "head" will become "curr", while the head
* in its previous callstack is the real head after this call.
* Setting up a break point will make all of this crystal clear.
*/
curr = reverseKGroup(curr, k);
while (count-- > 0) {
ListNode temp = head.next;
head.next = curr;
curr = head;
head = temp;
}
head = curr;
}
// we run out of nodes before we hit count == k, so we'll just directly return head in this case as well
return head;
}
use of com.fishercoder.common.classes.ListNode in project Leetcode by fishercoder1534.
the class _445 method popIntoStack.
private Deque<Integer> popIntoStack(ListNode head) {
ListNode tmp = head;
Deque<Integer> stack = new ArrayDeque<>();
while (tmp != null) {
stack.push(tmp.val);
tmp = tmp.next;
}
return stack;
}
use of com.fishercoder.common.classes.ListNode in project Leetcode by fishercoder1534.
the class CommonUtils method reverseList.
/**
* If you want to print the reversed list out, you need to return the reversed list's head,
* which was the end node of the original node. using the following function.
*/
public static ListNode reverseList(ListNode head) {
if (head == null || head.next == null) {
return head;
}
ListNode previous;
ListNode current;
ListNode next;
previous = head;
current = head.next;
while (current != null) {
next = current.next;
current.next = previous;
previous = current;
current = next;
}
head.next = null;
return previous;
}
use of com.fishercoder.common.classes.ListNode in project Leetcode by fishercoder1534.
the class CommonUtils method printList.
public static void printList(final ListNode head) {
ListNode temp = head;
System.out.println("--------------------------------------------");
while (temp != null) {
System.out.print(temp.val);
temp = temp.next;
if (temp != null) {
System.out.print("->");
}
}
System.out.println();
}
use of com.fishercoder.common.classes.ListNode in project Leetcode by fishercoder1534.
the class _142 method detectCycle.
public ListNode detectCycle(ListNode head) {
ListNode slow = head;
ListNode fast = head;
while (fast != null && fast.next != null) {
slow = slow.next;
fast = fast.next.next;
if (slow == fast) {
ListNode slow2 = head;
while (slow2 != slow) {
slow = slow.next;
slow2 = slow2.next;
}
return slow;
}
}
return null;
}
Aggregations