deleteNode for singly linked list java -


public void deletenode(student targetnode) {      node position = head;     node nextposition1;     node nextposition2;      while (position.getlink() != null) {          if (position.getlink().getdata().equals(targetnode)) {              nextposition1 = position.getlink();             nextposition2 = nextposition1.getlink();             position.setlink(nextposition2);          } else {             position = position.getlink();          }     } } 

i can delete specific nodes can't delete first node.

your loop checking next link in position equality target node. thus, it'll never @ first value (the head). easiest way fix add clause check equality explicitly against head, , if exists, advance head it's link otherwise enter while loop checks against future links. believe want add break; if clause remove link unless you're looking potentially remove several nodes , not 1 (as function name suggest).

public void deletenode(student targetnode) {     node position = head;     if (position.getdata().equals(targetnode)) {         head = position.getlink();     }     else {          node nextposition1;         node nextposition2;         while (position.getlink() != null) {              if (position.getlink().getdata().equals(targetnode)) {                  nextposition1 = position.getlink();                 nextposition2 = nextposition1.getlink();                 position.setlink(nextposition2);              } else {                 position = position.getlink();              }         }     } } 

the alternative check current position (keeping track of previous node) , remove once it's equal targetnode. if previous node null, know we're looking @ head (and should update head), else we're looking @ middle/end link in list.

public void deletenode(student targetnode) {     node position = head;     node previous = null;     while (position != null) {     {         if (position.getdata().equals(targetnode)) {             if (previous == null) {                 head = position.getlink();             }             else {                 previous.setlink(position.getlink());             }             break;         }         else {             previous = position;             position = position.getlink();         }     } } 

Comments

Popular posts from this blog

how to insert data php javascript mysql with multiple array session 2 -

multithreading - Exception in Application constructor -

windows - CertCreateCertificateContext returns CRYPT_E_ASN1_BADTAG / 8009310b -