1

So I wrote a linkList that holds a student reference and a next reference. I have no issue with insertion. On the other hand, I need help with deletion and finding the item. So basically I'm using the find method to find a student reference to a string. Then using a delete method to delete the node corresponding with that reference.

   public void deleteStudentNode(StudentNode delete)
   { 
          StudentNode it = new StudentNode();
          delete = shead;
          it = shead; 
          //StudentNode b = new StudentNode();

          while(it.getSptr() != findStudentByName(""))        
          {
             delete = it;
             it = it.getSptr();
          }
          delete.setSptr(null);         
          setShead(delete);
          //d.setStudent(null);                
   }

   public StudentNode findStudentByName (String findName)
   {
            StudentNode find = shead;

      while(find.getStudent().getName() != findName)
      {
         if(find.getSptr() == null)

            return null;

         else

            find = find.getSptr();      
      }
                  return find; 
   }
cheesey
  • 516
  • 7
  • 18
Qwanny
  • 11
  • 6
  • 1
    I don't know if it is the only problem, but you should use `equals` to compare strings instead of `==`, see [this answer](http://stackoverflow.com/questions/513832/how-do-i-compare-strings-in-java/513839#513839). – Robin Krahl Mar 21 '17 at 14:49
  • @RobinKrahl sorry, didn't read your comment properly. Yes, for comparing strings you should use `equals` – esin88 Mar 21 '17 at 14:51
  • @esin88 . I Notice that but I'm not understanding the approach. its confusing me – Qwanny Mar 21 '17 at 14:54

1 Answers1

0

I would recommend implementing Iterable interface for your one-linked list. After that all you need to do is

public void deleteByName(StudentList studentList, String nameToDelete) {
    Iterator iterator = studentList.iterator();
    while (iterator.hasNext()) {
        if(iterator.next().getName().equals(nameToDelete)) {
            iterator.remove();
        }
    }
}

Hint, for iterating through one-linked list you need 2 pointers: for current element and for previous.

esin88
  • 3,091
  • 30
  • 35
  • thank you for your answer, ive like it so far. The only issue is I cant use this interface. have to strictly use the methods I have. but I understand the iterator you have. – Qwanny Mar 21 '17 at 15:02
  • @Qwanny you mean you have to use exactly these 2 methods? `deleteStudentNode(StudentNode delete)` and `findStudentByName (String findName)`? – esin88 Mar 21 '17 at 16:31
  • no problem now ive actually gotten it to work. now I'm trying to for a link list inside of another one – Qwanny Mar 23 '17 at 03:28