The Artima Developer Community
Sponsored Link

Java Answers Forum
help with deleting a node in a linked list

2 replies on 1 page. Most recent reply: Aug 3, 2002 7:00 AM by Don Hill

Welcome Guest
  Sign In

Go back to the topic listing  Back to Topic List Click to reply to this topic  Reply to this Topic Click to search messages in this forum  Search Forum Click for a threaded view of the topic  Threaded View   
Previous Topic   Next Topic
Flat View: This topic has 2 replies on 1 page
Leslie Jo

Posts: 22
Nickname: leeloo
Registered: Jul, 2002

help with deleting a node in a linked list Posted: Aug 2, 2002 7:05 PM
Reply to this message Reply
Advertisement
hello, below is a code i wrote for finding a node in a linked list, and deleting it


// Locate the node containing the data object that matches (use the
// equals method from CityLocation) aCity, and remove it from the list.
// Return a link to the data object contained in the deleted node.
// Return null if the node can not be located.
// The complexity is O(n)
public CityLocation delete (CityLocation aCity) {
if (!isEmpty()) { // checks for empty list

// if list is not empty, create 2 variables to traverse list
// one holds the current element, and the other the previous one
// assumes direction is from head to tail
CityLocationDLNode nextNode = this.head.next;
CityLocationDLNode currNode = this.head;

// if only one node in list
if (nextNode == null) {
this.head = null;
}

// traverse list in search of target node
while (nextNode != null) {
// checks if data element of node is target value
if (location.info.equals (aCity)) {
// if found, delete element by skipping over next node
currNode = nextNode;
} // end if
} // end while
} // end outer if
return location.info;


Leslie Jo

Posts: 22
Nickname: leeloo
Registered: Jul, 2002

Re: help with deleting a node in a linked list Posted: Aug 2, 2002 7:06 PM
Reply to this message Reply
however i couldnt get it to work, can any one see why?

Don Hill

Posts: 70
Nickname: ssswdon
Registered: Jul, 2002

Re: help with deleting a node in a linked list Posted: Aug 3, 2002 7:00 AM
Reply to this message Reply
Leslie,

Why don't you take a look at the java.util.LinkedList API. All you need to do is iterate through the list performaing a cast on the object as you pull them out, they need to be cast and then compared, you should implment the equals method on your objects. This way its easy to compare.

HTH

http://devcenter2.silverstream.com/SilverHelp37/Docs/Help/java/jdk/api/index.html

Flat View: This topic has 2 replies on 1 page
Topic: Serious stuff ........ Java/C++ Previous Topic   Next Topic Topic: Flaw in inheritance and overloading combination?

Sponsored Links



Google
  Web Artima.com   

Copyright © 1996-2019 Artima, Inc. All Rights Reserved. - Privacy Policy - Terms of Use