Skip to content

Commit

Permalink
update 206 java
Browse files Browse the repository at this point in the history
  • Loading branch information
yennanliu committed May 25, 2024
1 parent 875eb57 commit 20f1677
Show file tree
Hide file tree
Showing 2 changed files with 51 additions and 1 deletion.
Original file line number Diff line number Diff line change
Expand Up @@ -24,13 +24,22 @@ public ListNode reverseList(ListNode head) {
*
* 4 operations
*
* Step 0) set _prev as null
* step 1) cache next
* step 2) point cur to prev
* step 3) move prev to cur
* step 3) move prev to cur (NOTE !!! the step)
* step 4) move cur to next
*/
ListNode _next = head.next;
head.next = _prev;
/** NOTE !!!
*
* -> have to assign _prev val to head first,
* then assign head val to _next,
* since if we assign head val to _next first,
* then head is changed (become "_next" node), then we will assign _prev to _next node,
* which is WRONG
*/
_prev = head;
head = _next;
}
Expand Down
41 changes: 41 additions & 0 deletions leetcode_java/src/main/java/dev/workspace3.java
Original file line number Diff line number Diff line change
Expand Up @@ -1839,5 +1839,46 @@ public int getSum(List<Integer> cur) {
return res;
}

// LC 206
public ListNode reverseList_(ListNode head) {

if (head == null) {
return null;
}

ListNode root = new ListNode();
ListNode _prev = null;
root.next = _prev;

while (head != null) {
/**
* NOTE !!!!
*
* 4 operations
*
* Step 0) set _prev as null
* step 1) cache next
* step 2) point cur to prev
* step 3) move prev to cur (NOTE !!! the step)
* step 4) move cur to next
*/
ListNode _next = head.next;
head.next = _prev;
/** NOTE !!!
*
* -> have to assign _prev val to head first,
* then assign head val to _next,
* since if we assign head val to _next first,
* then head is changed (become "_next" node), then we will assign _prev to _next node,
* which is WRONG
*/
_prev = head;
head = _next;
}

// NOTE!!! we return _prev here, since it's now "new head"
return root.next; //_prev;
}


}

0 comments on commit 20f1677

Please sign in to comment.