Skip to content

Instantly share code, notes, and snippets.

@ALEXOTANO
Created February 18, 2021 01:41
Show Gist options
  • Save ALEXOTANO/98027c4bf95b56e4ad43c86a8f4bc927 to your computer and use it in GitHub Desktop.
Save ALEXOTANO/98027c4bf95b56e4ad43c86a8f4bc927 to your computer and use it in GitHub Desktop.
Remove Nth Node From End of List
class LinkedList {
constructor(){
this.head = null;
}
removeNode(index2Remove) {
if(index2Remove == 0){
this.head = this.head.next;
return
}
let prev;
let curr = this.head;
let counter = 0;
while( counter < index2Remove ) {
prev = curr;
curr = curr.next;
counter++;
}
prev.next = curr.next ? curr.next : null;
}
getSize(){
let size = 0
/* find out the index to be removed */
let node = this.head;
while(node){
size++;
node = node.next;
}
return size
}
}
removeNthFromEnd = function(head, n) {
let list = new LinkedList();
list.head = head
let index2Remove = list.getSize() - n;
list.removeNode(index2Remove)
return list.head
};
<?php
class LinkedList {
public function __construct($var = NULL) {
$this->head = $var;
}
public function removeNode($index2Remove) {
if($index2Remove == 0){
$this->head = $this->head->next;
return;
}
$prev = NULL;
$curr = $this->head;
$counter = 0;
while( $counter < $index2Remove ) {
$prev = $curr;
$curr = $curr->next;
$counter++;
}
$prev->next = $curr->next ? $curr->next : NULL;
}
public function getSize(){
$size = 0;
/* find out the index to be removed */
$node = $this->head;
while($node){
$size++;
$node = $node->next;
}
return $size;
}
}
class Solution {
/**
* @param ListNode $head
* @param Integer $n
* @return ListNode
*/
function removeNthFromEnd($head, $n) {
$list = new LinkedList();
$list->head = $head;
$index2Remove = $list->getSize();
$index2Remove -= $n;
$list->removeNode($index2Remove);
return $list->head;
}
}
@charlie-vallejo
Copy link

Hola Alex, solo para comentarte, he leído mas con calma tu código en php y solo para comentarte, desde php 7.4 puedes crear variables tipificables y de igual manera devolver valores tipificables, en tu constructor (tanto en js como en php) y me ha llamado el uso de la propiedad next en arreglos, para serte honesto la había visto antes pero no la había usado, gracias por el dato ejejeje.

Igual creo se puede optimizar el código y el tiempo de ejecución si se quita del constructor la variable head y mejor se pasa como parámetro en donde la uses, usar la clase LinkedList mas como un helper. Saludos

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment