@@ -1330,4 +1330,56 @@ class Solution:
13301330 head.next = n2
13311331 head = n1
13321332 return dummy.next
1333+ ```
1334+
1335+ ### 2-10) Plus One Linked List
1336+ ```java
1337+ // java
1338+ // LC 369
1339+ // V1
1340+ // IDEA : LINKED LIST OP (gpt)
1341+ /**
1342+ * Step 1) reverse linked list
1343+ * Step 2) plus 1, bring `carry` to next digit if curSum > 9, ... repeat for all nodes
1344+ * Step 3) reverse linked list again
1345+ */
1346+ public ListNode plusOne_1(ListNode head) {
1347+ if (head == null ) return new ListNode (1 ); // Handle edge case
1348+
1349+ // Reverse the linked list
1350+ head = reverseList (head );
1351+
1352+ // Add one to the reversed list
1353+ ListNode current = head;
1354+ int carry = 1 ; // Start with adding one
1355+
1356+ while (current != null && carry > 0 ) {
1357+ int sum = current. val + carry;
1358+ current. val = sum % 10 ; // Update the current node value
1359+ carry = sum / 10 ; // Calculate carry for the next node
1360+ if (current. next == null && carry > 0 ) {
1361+ current. next = new ListNode (carry); // Add a new node for carry
1362+ carry = 0 ; // No more carry after this
1363+ }
1364+ current = current. next;
1365+ }
1366+
1367+ // Reverse the list back to original order
1368+ return reverseList (head );
1369+ }
1370+
1371+ // Utility to reverse a linked list
1372+ private ListNode reverseList(ListNode head) {
1373+ ListNode prev = null ;
1374+ ListNode current = head;
1375+
1376+ while (current != null ) {
1377+ ListNode next = current. next; // Save the next node
1378+ current. next = prev; // Reverse the link
1379+ prev = current; // Move prev forward
1380+ current = next; // Move current forward
1381+ }
1382+
1383+ return prev;
1384+ }
13331385```
0 commit comments