|
| 1 | +packageeasy; |
| 2 | + |
| 3 | +importclasses.ListNode; |
| 4 | + |
| 5 | +/**237. Delete Node in a Linked List QuestionEditorial Solution My Submissions |
| 6 | +Total Accepted: 96741 |
| 7 | +Total Submissions: 218247 |
| 8 | +Difficulty: Easy |
| 9 | +Write a function to delete a node (except the tail) in a singly linked list, given only access to that node. |
| 10 | +
|
| 11 | +Supposed the linked list is 1 -> 2 -> 3 -> 4 and you are given the third node with value 3, the linked list should become 1 -> 2 -> 4 after calling your function. |
| 12 | +
|
| 13 | +Hide Company Tags Adobe Apple Microsoft |
| 14 | +Hide Tags Linked List |
| 15 | +Hide Similar Problems (E) Remove Linked List Elements |
| 16 | +*/ |
| 17 | +publicclassDeleteNodeInALinkedList { |
| 18 | + |
| 19 | +/**We're not really deleting the node, but we're overwriting this node's value with its successor's value, |
| 20 | + * and then append its successor's successor to its new successor. |
| 21 | + * |
| 22 | + * In graph, it's like this: |
| 23 | + * Given this list: 1->2->3->4->null and only access to this to-be-deleted node 3 |
| 24 | + * we overwrite 3 with 4, and then assign null to be 4's next.*/ |
| 25 | +publicvoiddeleteNode(ListNodenode) { |
| 26 | +node.val =node.next.val; |
| 27 | +node.next =node.next.next; |
| 28 | + } |
| 29 | + |
| 30 | +} |