Skip to content

Commit

Permalink
fix/update cheatsheet
Browse files Browse the repository at this point in the history
  • Loading branch information
yennanliu committed Dec 22, 2024
1 parent 0d1b3d8 commit 9ea1b14
Show file tree
Hide file tree
Showing 2 changed files with 55 additions and 3 deletions.
6 changes: 3 additions & 3 deletions doc/cheatsheet/difference_array.md
Original file line number Diff line number Diff line change
Expand Up @@ -127,7 +127,7 @@ return Arrays.copyOfRange(tmp, 1, n+1);

## 2) LC Example

## Range Addition
### 2-1) Range Addition

```java
// java
Expand Down Expand Up @@ -186,7 +186,7 @@ class Solution {
}
```

### Corporate Flight Bookings
### 2-2) Corporate Flight Bookings

```java
// java
Expand Down Expand Up @@ -214,7 +214,7 @@ class Solution {
}
```

### Car Pooling
### 2-3) Car Pooling

```java
// java
Expand Down
52 changes: 52 additions & 0 deletions doc/cheatsheet/linked_list.md
Original file line number Diff line number Diff line change
Expand Up @@ -1330,4 +1330,56 @@ class Solution:
head.next = n2
head = n1
return dummy.next
```

### 2-10) Plus One Linked List
```java
// java
// LC 369
// V1
// IDEA : LINKED LIST OP (gpt)
/**
* Step 1) reverse linked list
* Step 2) plus 1, bring `carry` to next digit if curSum > 9, ... repeat for all nodes
* Step 3) reverse linked list again
*/
public ListNode plusOne_1(ListNode head) {
if (head == null) return new ListNode(1); // Handle edge case

// Reverse the linked list
head = reverseList(head);

// Add one to the reversed list
ListNode current = head;
int carry = 1; // Start with adding one

while (current != null && carry > 0) {
int sum = current.val + carry;
current.val = sum % 10; // Update the current node value
carry = sum / 10; // Calculate carry for the next node
if (current.next == null && carry > 0) {
current.next = new ListNode(carry); // Add a new node for carry
carry = 0; // No more carry after this
}
current = current.next;
}

// Reverse the list back to original order
return reverseList(head);
}

// Utility to reverse a linked list
private ListNode reverseList(ListNode head) {
ListNode prev = null;
ListNode current = head;

while (current != null) {
ListNode next = current.next; // Save the next node
current.next = prev; // Reverse the link
prev = current; // Move prev forward
current = next; // Move current forward
}

return prev;
}
```

0 comments on commit 9ea1b14

Please sign in to comment.