Linked List Flashcards

1
Q
  1. Reverse Linked List
A

public ListNode reverseList(ListNode head) {
ListNode curr = head;
ListNode prev = null;

        while (curr != null) {
            ListNode temp = curr.next; // temp prevents cycle w/ prev
            curr.next = prev;
            prev = curr;
            curr = temp;
        }
    return prev;
}
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q
  1. Linked List Cycle
A
public boolean hasCycle(ListNode head) {
        if (head == null || head.next == null) {
            return false;
        }
        ListNode slow = head;
        ListNode fast = head;
        boolean isCycle = false;
        while (fast.next != null && fast.next.next != null) {
            // inc slow 1, fast 2
            slow = slow.next;
            fast = fast.next.next;
            if (fast == slow) { // actual node, not just data
                isCycle = true;
                break;
            }
        }
        return isCycle;
    }
How well did you know this?
1
Not at all
2
3
4
5
Perfectly