View on GitHub

SCRATCH PAD

No polish, just pulse

Striver’s SDE Sheet Notes (Day 5: LinkedList)

1. Reverse Linked List

  public ListNode reverseList(ListNode head) {
      ListNode prev = null;
      ListNode current = head;
      while (current != null) {
          ListNode next = current.next;
          current.next = prev;
          prev = current;
          current = next;
      }
      return prev;
  }
  

2. Middle of the Linked List

  public ListNode middleNode(ListNode head) {
      ListNode slow = head;
      ListNode fast = head;
      while (fast != null && fast.next != null) {
          slow = slow.next;
          fast = fast.next.next;
      }
      return slow;
  }
  

3. Merge Two Sorted Lists

  public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
      ListNode dummy = new ListNode(0);
      ListNode current = dummy;
      while (l1 != null && l2 != null) {
          if (l1.val < l2.val) {
              current.next = l1;
              l1 = l1.next;
          } else {
              current.next = l2;
              l2 = l2.next;
          }
          current = current.next;
      }
      current.next = (l1 != null) ? l1 : l2;
      return dummy.next;
  }
  

4. Remove N-th Node From End of List

  public ListNode removeNthFromEnd(ListNode head, int n) {
      ListNode dummy = new ListNode(0);
      dummy.next = head;
      ListNode slow = dummy;
      ListNode fast = dummy;
      for (int i = 1; i <= n + 1; i++) {
          fast = fast.next;
      }
      while (fast != null) {
          slow = slow.next;
          fast = fast.next;
      }
      slow.next = slow.next.next;
      return dummy.next;
  }
  

5. Palindrome Linked List

  public boolean isPalindrome(ListNode head) {
      if (head == null || head.next == null) return true;
      ListNode slow = head;
      ListNode fast = head;
      while (fast != null && fast.next != null) {
          slow = slow.next;
          fast = fast.next.next;
      }
      ListNode prev = null;
      while (slow != null) {
          ListNode next = slow.next;
          slow.next = prev;
          prev = slow;
          slow = next;
      }
      while (prev != null) {
          if (head.val != prev.val) return false;
          head = head.next;
          prev = prev.next;
      }
      return true;
  }