Linked List Flashcards
1
Q
- 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; }
2
Q
- 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; }