Java - Writing method for public int indexOf(T element) in a double linked list - linked-list

Below I have the int indexOf(T element) method for a double linked list. I need help with the code to make sure it functions properly. The method should return the first occurence of the element in the list or -1 if element is not in the list. Below is the node class it uses. The IUDoubleLinkedList.java class implements IndexedUnsortedList.java which is where the indexOf method comes from. I tried using my indexOf method from my single linked list class but it's not the same so I hope to understand why it would be different and what code is used that is different between the the single and double linked list.
public class IUDoubleLinkedList<T> implements IndexedUnsortedList<T> {
private Node<T> head, tail;
private int size;
private int modCount;
public IUDoubleLinkedList() {
head = tail = null;
size = 0;
modCount = 0;
This is the indexOf(T element) method
#Override
public int indexOf(T element) {
// TODO Auto-generated method stub
return 0;
}
Below is the Node.java class it uses
public class Node<T> {
private Node<T> nextNode;
private T element;
private Node<T> prevNode;
/**
* Creates an empty node.
*/
public Node() {
nextNode = null;
element = null;
}
/**
* Creates a node storing the specified element.
*
* #param elem
* the element to be stored within the new node
*/
public Node(T element) {
nextNode = null;
this.element = element;
setPrevNode(null);
}
/**
* Returns the node that follows this one.
*
* #return the node that follows the current one
*/
public Node<T> getNextNode() {
return nextNode;
}
/**
* Sets the node that follows this one.
*
* #param node
* the node to be set to follow the current one
*/
public void setNextNode(Node<T> nextNode) {
this.nextNode = nextNode;
}
/**
* Returns the element stored in this node.
*
* #return the element stored in this node
*/
public T getElement() {
return element;
}
/**
* Sets the element stored in this node.
*
* #param elem
* the element to be stored in this node
*/
public void setElement(T element) {
this.element = element;
}
#Override
public String toString() {
return "Element: " + element.toString() + " Has next: " + (nextNode != null);
}
public Node<T> getPrevNode() {
return prevNode;
}
public void setPrevNode(Node<T> prevNode) {
this.prevNode = prevNode;
}
}

Check the following code, hope I helped you!
Insert item at head as well as tail end
public void insertItem(T elem) {
/* if head and tail both are null*/
if(head == null || tail == null) {
head = new Node<T>(elem);
tail = new Node<T>(elem);
}else {
Node<T> tempItem = new Node<T>();
tempItem.setElement(elem);
/* insert at head end /*
tempItem.setNextNode(head);
head.setPrevNode(tempItem);
head = tempItem;
Node<T> tempItem1 = new Node<T>();
tempItem1.setElement(elem);
/* append at tail end */
tail.setNextNode(tempItem1);
tempItem1.setPrevNode(tail);
tail = tempItem1;
}
size += 1;
}
Print item from head end
public void printItemsFromHead() {
while(head != null) {
System.out.print(head.getElement()+" --> ");
head = head.getNextNode();
}
}
Print item from tail end
public void printItemsFromTail() {
Node<T> temp = null;
while(tail != null) {
temp = tail;
System.out.print(tail.getElement()+" --> ");
tail = tail.getPrevNode();
}
/*System.out.println();
while(temp != null) {
System.out.print(temp.getElement()+" --> ");
temp = temp.getNextNode();
}*/
}
Implemention of indexOf function
#Override
public int indexOf(T element) {
int result = -1;
int headIndex = 0;
int tailIndex = size;
while(head != null && tail != null) {
if(head.getElement().equals(element)) {
result = headIndex;
break;
}
/*
if(tail.getElement().equals(element)) {
result = tailIndex;
break;
} */
head = head.getNextNode();
tail = tail.getPrevNode();
headIndex += 1;
tailIndex -= 1;
}
return result;
}
Driver class
public class Driver {
#SuppressWarnings({ "rawtypes", "unchecked" })
public static <T> void main(String[] args) {
UDoubleLinkedList uDoubleLinkedList = new UDoubleLinkedList();
uDoubleLinkedList.insertItem(1);
uDoubleLinkedList.insertItem(2);
uDoubleLinkedList.insertItem(3);
uDoubleLinkedList.insertItem(4);
uDoubleLinkedList.insertItem(5);
System.out.println(uDoubleLinkedList.indexOf(1));
}
}

Related

Can I use class methods inside factory constructor via Dart

I have the below code that is creating the PriortyQueue structure using Dart. But since I cannot use heapify function inside the Constructor or factory constructor I cannot initialize PQ with an existing set of List. Can somebody guide me and show me how I can use heapify while creating PQ instance so I can initialize it with an existing List? Also If you have any other suggestions against doing something like this please also help me as well. thank you
class PriorityQueue<T extends Comparable<T>> {
List<T?> _tree;
PriorityQueue._(List<T?> tree) : _tree = tree;
factory PriorityQueue([List<T>? array]) {
List<T?> newArray = [null, ...array ?? []];
// ignore: todo
//TODO: missing heapify
return PriorityQueue._(newArray);
}
void insert(T node) {
_tree.add(node);
_swim(_tree.length - 1);
}
T getTop() {
_swap(1, _tree.length - 1);
T top = _tree.removeLast() as T;
_sink(1);
return top;
}
List<T> _heapify(List<T> array) {
int sinkNodeIndex = (array.length - 1) ~/ 2;
while (sinkNodeIndex >= 1) {
_sink(sinkNodeIndex);
sinkNodeIndex--;
}
}
void _sink(int nodeIndex) {
int leftChildIndex = nodeIndex * 2;
int rightChildIndex = leftChildIndex + 1;
int minNodeIndex = leftChildIndex;
// index can be unreachable
T? leftChild =
leftChildIndex >= _tree.length ? null : _tree[leftChildIndex];
T? rightChild =
rightChildIndex >= _tree.length ? null : _tree[rightChildIndex];
if (leftChild == null) {
return;
}
if (rightChild != null && leftChild.compareTo(rightChild) > 0) {
minNodeIndex = rightChildIndex;
}
if ((_tree[minNodeIndex] as T).compareTo(_tree[nodeIndex] as T) < 0) {
_swap(nodeIndex, minNodeIndex);
_sink(minNodeIndex);
}
}
void _swim(int nodeIndex) {
if (nodeIndex <= 1) return;
int parentIndex = nodeIndex ~/ 2;
if ((_tree[nodeIndex] as T).compareTo(_tree[parentIndex] as T) < 0) {
_swap(nodeIndex, parentIndex);
_swim(parentIndex);
}
}
void _swap(int i, int j) {
T temp = _tree[i] as T;
_tree[i] = _tree[j];
_tree[j] = temp;
}
#override
String toString() {
return _tree.toString();
}
}
I would make all the helper functions. _heapify, _sink/_swim, even _swap, be static functions which take the list as argument.
Then you can use them from anywhere, including inside the factory constructor.
Alternatively, you can change the constructor to returning:
return PriorityQueue._(newArray).._heapify();
This creates the PriorityQueue object, and then calls the _heapify method on it, before returning the value.
(I'd also make _tree have type List<T> and not insert the extra null at the beginning. It's more efficient to add/subtract 1 from indices than it is to cast to T.)
I ended up doing like Irn's first suggestion. But when I do functions static they lost Type of the class so I needed to specify for each function. Also, making List<T?> instead of List ended up with me fighting against the compiler.
class PriorityQueue<T extends Comparable<T>> {
List<T?> _tree;
PriorityQueue._(List<T?> tree) : _tree = tree;
factory PriorityQueue([List<T>? array]) {
List<T?> newArray = [null, ...array ?? []];
_heapify(newArray);
return PriorityQueue._(newArray);
}
bool get isNotEmpty {
return _tree.isNotEmpty;
}
void insert(T node) {
_tree.add(node);
_swim(_tree, _tree.length - 1);
}
void insertMultiple(List<T> array) {
for (var element in array) {
insert(element);
}
}
T? removeTop() {
if (_tree.length == 1) return null;
_swap(_tree, 1, _tree.length - 1);
T top = _tree.removeLast() as T;
_sink(_tree, 1);
return top;
}
void removeAll() {
_tree = [null];
}
static void _heapify<T extends Comparable<T>>(List<T?> array) {
int sinkNodeIndex = (array.length - 1) ~/ 2;
while (sinkNodeIndex >= 1) {
_sink(array, sinkNodeIndex);
sinkNodeIndex--;
}
}
static void _sink<T extends Comparable<T>>(List<T?> tree, int nodeIndex) {
int leftChildIndex = nodeIndex * 2;
int rightChildIndex = leftChildIndex + 1;
int minNodeIndex = leftChildIndex;
T? leftChild = leftChildIndex >= tree.length ? null : tree[leftChildIndex];
T? rightChild =
rightChildIndex >= tree.length ? null : tree[rightChildIndex];
if (leftChild == null) {
return;
}
if (rightChild != null && leftChild.compareTo(rightChild) > 0) {
minNodeIndex = rightChildIndex;
}
if ((tree[minNodeIndex] as T).compareTo(tree[nodeIndex] as T) < 0) {
_swap(tree, nodeIndex, minNodeIndex);
_sink(tree, minNodeIndex);
}
}
static void _swim<T extends Comparable<T>>(List<T?> tree, int nodeIndex) {
if (nodeIndex <= 1) return;
int parentIndex = nodeIndex ~/ 2;
if ((tree[nodeIndex] as T).compareTo(tree[parentIndex] as T) < 0) {
_swap(tree, nodeIndex, parentIndex);
_swim(tree, parentIndex);
}
}
static void _swap<T extends Comparable<T>>(List<T?> tree, int i, int j) {
T temp = tree[i] as T;
tree[i] = tree[j];
tree[j] = temp;
}
#override
String toString() {
return _tree.toString();
}
}

Is this the best way to get all elements & attributes in an XML file using Saxon?

Our program displays a tree control showing the metadata structure of the XML file they are using as a datasource. So it displays all elements & attributes in use in the XML file, like this:
Employees
Employee
FirstName
LastName
Orders
Order
OrderId
For the case where the user does not pass us a XSD file, we need to walk the XML file and build up the metadata structure.
The full code for this is at SaxonQuestions.zip, TestBuildTree.java and is also listed below.
I am concerned that my code is not the most efficient, or maybe even wrong. It works, but it works on the 3 XML files I tested it on. My questions are:
What is the best way to get the root element from the DOM? Is it walking the children of the DOM root node?
What is the best way to determine if an element has data (as opposed to just child elements)? The best I could come up with throws an exception if not and I don't think code executing the happy path should throw an exception.
What is the best way to get the class of the data held in an element or attribute? Is it: ((XdmAtomicValue)((XdmNode)currentNode).getTypedValue()).getValue().getClass();
Is the best way to walk all the nodes to use XdmNode.axisIterator? And to do so as I have in this code?
TestBuildTree.java
import net.sf.saxon.s9api.*;
import java.io.File;
import java.io.FileInputStream;
import java.util.ArrayList;
import java.util.List;
public class TestBuildTree {
public static void main(String[] args) throws Exception {
XmlDatasource datasource = new XmlDatasource(
new FileInputStream(new File("files", "SouthWind.xml").getCanonicalPath()),
null);
// Question:
// Is this the best way to get the root element?
// get the root element
XdmNode rootNode = null;
for (XdmNode node : datasource.getXmlRootNode().children()) {
if (node.getNodeKind() == XdmNodeKind.ELEMENT) {
rootNode = node;
break;
}
}
TestBuildTree buildTree = new TestBuildTree(rootNode);
Element root = buildTree.addNode();
System.out.println("Schema:");
printElement("", root);
}
private static void printElement(String indent, Element element) {
System.out.println(indent + "<" + element.name + "> (" + (element.type == null ? "null" : element.type.getSimpleName()) + ")");
indent += " ";
for (Attribute attr : element.attributes)
System.out.println(indent + "=" + attr.name + " (" + (attr.type == null ? "null" : attr.type.getSimpleName()) + ")");
for (Element child : element.children)
printElement(indent, child);
}
protected XdmItem currentNode;
public TestBuildTree(XdmItem currentNode) {
this.currentNode = currentNode;
}
private Element addNode() throws SaxonApiException {
String name = ((XdmNode)currentNode).getNodeName().getLocalName();
// Question:
// Is this the best way to determine that this element has data (as opposed to child elements)?
Boolean elementHasData;
try {
((XdmNode) currentNode).getTypedValue();
elementHasData = true;
} catch (Exception ex) {
elementHasData = false;
}
// Questions:
// Is this the best way to get the type of the element value?
// If no schema is it always String?
Class valueClass = ! elementHasData ? null : ((XdmAtomicValue)((XdmNode)currentNode).getTypedValue()).getValue().getClass();
Element element = new Element(name, valueClass, null);
// add in attributes
XdmSequenceIterator currentSequence;
if ((currentSequence = moveTo(Axis.ATTRIBUTE)) != null) {
do {
name = ((XdmNode) currentNode).getNodeName().getLocalName();
// Questions:
// Is this the best way to get the type of the attribute value?
// If no schema is it always String?
valueClass = ((XdmAtomicValue)((XdmNode)currentNode).getTypedValue()).getValue().getClass();
Attribute attr = new Attribute(name, valueClass, null);
element.attributes.add(attr);
} while (moveToNextInCurrentSequence(currentSequence));
moveTo(Axis.PARENT);
}
// add in children elements
if ((currentSequence = moveTo(Axis.CHILD)) != null) {
do {
Element child = addNode();
// if we don't have this, add it
Element existing = element.getChildByName(child.name);
if (existing == null)
element.children.add(child);
else
// add in any children this does not have
existing.addNewItems (child);
} while (moveToNextInCurrentSequence(currentSequence));
moveTo(Axis.PARENT);
}
return element;
}
// moves to element or attribute
private XdmSequenceIterator moveTo(Axis axis) {
XdmSequenceIterator en = ((XdmNode) currentNode).axisIterator(axis);
boolean gotIt = false;
while (en.hasNext()) {
currentNode = en.next();
if (((XdmNode) currentNode).getNodeKind() == XdmNodeKind.ELEMENT || ((XdmNode) currentNode).getNodeKind() == XdmNodeKind.ATTRIBUTE) {
gotIt = true;
break;
}
}
if (gotIt) {
if (axis == Axis.ATTRIBUTE || axis == Axis.CHILD || axis == Axis.NAMESPACE)
return en;
return null;
}
return null;
}
// moves to next element or attribute
private Boolean moveToNextInCurrentSequence(XdmSequenceIterator currentSequence)
{
if (currentSequence == null)
return false;
while (currentSequence.hasNext())
{
currentNode = currentSequence.next();
if (((XdmNode)currentNode).getNodeKind() == XdmNodeKind.ELEMENT || ((XdmNode)currentNode).getNodeKind() == XdmNodeKind.ATTRIBUTE)
return true;
}
return false;
}
static class Node {
String name;
Class type;
String description;
public Node(String name, Class type, String description) {
this.name = name;
this.type = type;
this.description = description;
}
}
static class Element extends Node {
List<Element> children;
List<Attribute> attributes;
public Element(String name, Class type, String description) {
super(name, type, description);
children = new ArrayList<>();
attributes = new ArrayList<>();
}
public Element getChildByName(String name) {
for (Element child : children) {
if (child.name.equals(name))
return child;
}
return null;
}
public void addNewItems(Element child) {
for (Attribute attrAdd : child.attributes) {
boolean haveIt = false;
for (Attribute attrExist : attributes)
if (attrExist.name.equals(attrAdd.name)) {
haveIt = true;
break;
}
if (!haveIt)
attributes.add(attrAdd);
}
for (Element elemAdd : child.children) {
Element exist = null;
for (Element elemExist : children)
if (elemExist.name.equals(elemAdd.name)) {
exist = elemExist;
break;
}
if (exist == null)
children.add(elemAdd);
else
exist.addNewItems(elemAdd);
}
}
}
static class Attribute extends Node {
public Attribute(String name, Class type, String description) {
super(name, type, description);
}
}
}
XmlDatasource.java
import com.saxonica.config.EnterpriseConfiguration;
import com.saxonica.ee.s9api.SchemaValidatorImpl;
import net.sf.saxon.Configuration;
import net.sf.saxon.lib.FeatureKeys;
import net.sf.saxon.s9api.*;
import net.sf.saxon.type.SchemaException;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.XMLReaderFactory;
import javax.xml.transform.Source;
import javax.xml.transform.sax.SAXSource;
import javax.xml.transform.stream.StreamSource;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
public class XmlDatasource {
/** the DOM all searches are against */
private XdmNode xmlRootNode;
private XPathCompiler xPathCompiler;
/** key == the prefix; value == the uri mapped to that prefix */
private HashMap<String, String> prefixToUriMap = new HashMap<>();
/** key == the uri mapped to that prefix; value == the prefix */
private HashMap<String, String> uriToPrefixMap = new HashMap<>();
public XmlDatasource (InputStream xmlData, InputStream schemaFile) throws SAXException, SchemaException, SaxonApiException, IOException {
boolean haveSchema = schemaFile != null;
// call this before any instantiation of Saxon classes.
Configuration config = createEnterpriseConfiguration();
if (haveSchema) {
Source schemaSource = new StreamSource(schemaFile);
config.addSchemaSource(schemaSource);
}
Processor processor = new Processor(config);
DocumentBuilder doc_builder = processor.newDocumentBuilder();
XMLReader reader = createXMLReader();
InputSource xmlSource = new InputSource(xmlData);
SAXSource saxSource = new SAXSource(reader, xmlSource);
if (haveSchema) {
SchemaValidator validator = new SchemaValidatorImpl(processor);
doc_builder.setSchemaValidator(validator);
}
xmlRootNode = doc_builder.build(saxSource);
xPathCompiler = processor.newXPathCompiler();
if (haveSchema)
xPathCompiler.setSchemaAware(true);
declareNameSpaces();
}
public XdmNode getXmlRootNode() {
return xmlRootNode;
}
public XPathCompiler getxPathCompiler() {
return xPathCompiler;
}
/**
* Create a XMLReader set to disallow XXE aattacks.
* #return a safe XMLReader.
*/
public static XMLReader createXMLReader() throws SAXException {
XMLReader reader = XMLReaderFactory.createXMLReader();
// stop XXE https://www.owasp.org/index.php/XML_External_Entity_(XXE)_Prevention_Cheat_Sheet#JAXP_DocumentBuilderFactory.2C_SAXParserFactory_and_DOM4J
reader.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);
reader.setFeature("http://xml.org/sax/features/external-general-entities", false);
reader.setFeature("http://xml.org/sax/features/external-parameter-entities", false);
return reader;
}
private void declareNameSpaces() throws SaxonApiException {
// saxon has some of their functions set up with this.
prefixToUriMap.put("saxon", "http://saxon.sf.net");
uriToPrefixMap.put("http://saxon.sf.net", "saxon");
XdmValue list = xPathCompiler.evaluate("//namespace::*", xmlRootNode);
if (list == null || list.size() == 0)
return;
for (int index=0; index<list.size(); index++) {
XdmNode node = (XdmNode) list.itemAt(index);
String prefix = node.getNodeName() == null ? "" : node.getNodeName().getLocalName();
// xml, xsd, & xsi are XML structure ones, not ones used in the XML
if (prefix.equals("xml") || prefix.equals("xsd") || prefix.equals("xsi"))
continue;
// use default prefix if prefix is empty.
if (prefix == null || prefix.isEmpty())
prefix = "def";
// this returns repeats, so if a repeat, go on to next.
if (prefixToUriMap.containsKey(prefix))
continue;
String uri = node.getStringValue();
if (uri != null && !uri.isEmpty()) {
xPathCompiler.declareNamespace(prefix, uri);
prefixToUriMap.put(prefix, uri);
uriToPrefixMap.put(uri, prefix); }
}
}
public static EnterpriseConfiguration createEnterpriseConfiguration()
{
EnterpriseConfiguration configuration = new EnterpriseConfiguration();
configuration.supplyLicenseKey(new BufferedReader(new java.io.StringReader(deobfuscate(key))));
configuration.setConfigurationProperty(FeatureKeys.SUPPRESS_XPATH_WARNINGS, Boolean.TRUE);
return configuration;
}
}

Linked List search method

I am practicing build a doubly linked list contains string value.
In find method, I have a NullPointer Exception
here is my code.
package LinkedList;
package LinkedList;
public class LinkedList {
// 노드 클래스
class Node {
String value;
Node prev;
Node next;
Node(String v, Node p, Node s) {
value = v;
prev = p;
next = s;
}
public String getValue() {
return value;
}
public Node getPrev() {
return prev;
}
public Node getNext() {
return next;
}
public void setPrev(Node p) {
prev = p;
}
public void setNext(Node n) {
next = n;
}
}
Node head;
Node tail;
int size = 0;
public LinkedList() {
head = new Node(null, null, null);
tail = new Node(null, head, null);
head.setNext(tail);
}
public int size() {
return size;
}
public boolean isEmpty() {
return size == 0;
}
public String first() {
if (isEmpty()) {
return null;
}
return head.getNext().getValue();
}
public String last() {
if (isEmpty()) {
return null;
}
return tail.getPrev().getValue();
}
public void addFirst(String value) {
addBetween(value, head, head.getNext());
}
public void addLast(String value) {
addBetween(value, tail.getPrev(), tail);
}
public void addBetween(String v, Node p, Node s) {
Node newNode = new Node(v, p, s);
p.setNext(newNode);
s.setPrev(newNode);
size++;
}
public String remove(Node node) {
Node p = node.getPrev();
Node s = node.getNext();
p.setNext(s);
s.setPrev(p);
size--;
return node.getValue();
}
public String removeFirst() {
if (isEmpty()) {
return null;
}
return remove(head.getNext());
}
public String removeLast() {
if (isEmpty()) {
return null;
}
return remove(tail.getPrev());
}
public void insert(String value) {
Node current = head;
// first
if (isEmpty()) {
addFirst(value);
} else {
// check
while (current.getNext() != tail || current.getValue().compareTo(value) > 0) {
current = current.getNext();
}
// last
if (current.getNext() == tail) {
addLast(value);
} else // between
{
addBetween(value, current.getNext(), current);
}
}
}
/* !!!!!!!!!!!!!! ERORR !!!!!!!!!!!! */
public void find(String value) {
Node current = head.getNext();
while ((current != null) || !(current.getValue().equals(value)))
current = current.getNext();
if (current.getValue().equals(value)) {
System.out.println("found " + value);
} else {
System.out.println("Not found " + value);
}
}
// • Traverse the list forwards and print
// 순회
public void fowardTraverse() {
Node current = head.getNext();
System.out.print(current.getValue());
while (current.getNext() != tail) {
current = current.getNext();
System.out.print(" -> " + current.getValue());
}
}
// • Traverse the list backwards and print
// 뒤로 순회
public void backwardTraverse() {
Node current = tail.getPrev();
System.out.print(current.getValue());
while (current.getPrev() != head) {
current = current.getPrev();
System.out.print(" -> " + current.getValue());
}
}
// • Delete a node from the list
// 지우기
public String delete(String value) {
return value;
}
// • Delete/destroy the list
// 파괴하기
public void destroy() {
}
public static void main(String[] args) {
// TODO Auto-generated method stubs
LinkedList a = new LinkedList();
a.insert("a");
a.insert("b");
a.insert("c");
a.insert("d");
a.insert("e");
a.insert("f");
a.insert("g");
a.insert("h");
a.insert("i");
// a.fowardTraverse();
a.find("a");
}
I don't understand why I get a nullpointException at the line,
It suppose to put a node contains a.
Make sure you check for Non-NULL before dereferencing:
Node current = head.getNext();
and
if (current.getValue().equals(value)) {
to be replaced by
Node current;
if(head != NULL) current = head.getNext();
and
if (current != NULL && current.getValue().equals(value)) {
Because your Head is empty...(No pun intended)
before Addfirst calling..your structure:
head=[null,null,tail],tail=[null,head,null];
you are sending ("a",head,tail)
and your storing it in new node making it a structure like:
head=[null,null,newNode]==>newNode["a",head,tail]==>tail[null,newNode,null]
So search will compare null to a (in find) giving you the error .....
---Edit 1:
#JanghyupLee, My Bad, Didn't do a closer look on find method...however , I found that in condition of "if" you are using condition
current != null || ......
After first line that is ( current=head.next)..current becomes not null..
which is causing the condition in while to ignore the right part of '||' (short circuit) until current has a value of null...
Once the current becomes null then it goes for the next statement to check for value..causing null pointer exception

Double Linked List

//I have a single linked list that looks like this
node head = new Node ();
head.info = 3;
head.next = new Node ();
head.next.info = 6 ();
head.next.next = new Node ();
head.next.next.info = 9;
head.next.next.next = null;
//How would I write a double linked list?
class Double Node
{
info;
doubleNode prev;
doubleNode next;
}
Here is the part for creating a double linked list and adding nodes to it.
You can update it by adding remove and insert functions as you want.
class Node{
Node prev;
Node next;
int value;
public Node(int value) {
this.value = value;
}
}
class DoubleLinkedList{
Node head;
Node tail;
public DoubleLinkedList(Node head) {
this.head = head;
this.tail = head;
head.next = null;
head.prev = null;
}
public void addNode(Node node){
tail.next = node;
node.prev = tail;
tail = node;
}
}
public class Main {
public static void main(String args[]){
Node head= new Node(3);
DoubleLinkedList list = new DoubleLinkedList(head);
list.addNode(new Node(5));
list.addNode(new Node(6));
list.addNode(new Node(7));
list.addNode(new Node(8));
}
}
This would be the idea:
node head = new Node();
head.info = 3;
node prev, actual, next;
prev = head;
actual.prev = prev;
actual.info = 6;
actual = actual.next = new Node();
actual.prev = prev;
actual = actual.next = new Node();
actual.info = 9;
...
Assuming that you will have the behavior in your example, you can automate it with a function, in c# would be something like:
function GetDoubleLinkedList(Node head, int from, int end, int jumps)
{
head.info = from;
node prev = head, actual, next;
for(var i = from+jumps; i <= end; i+=jumps)
{
actual.prev = prev;
actual.info = i;
actual = actual.next = new Node();
}
actual.info = end;
return head;
}
//...
//then you can do
node head = new Node();
head = GetDoubleLinkedList(head, 3, 9, 3);
//...
Double linked list are like single linked list with the exception that they have two pointer in the declaration of structure
a previous pointer and a next pointer
For sample implementation see this link
Here is an implementation of a DoubleLinkedList in Java (along with some examples that might help you understand how it's working):
public class Node {
public int value;
public Node prev;
public Node next;
public Node(int value) {
this.value = value;
this.prev = null;
}
public Node(int value, Node prev) {
this.value = value;
this.prev = prev;
}
public Node add(int value) {
if(this.next == null) {
this.next = new Node(value, this);
} else {
this.next.add(value);
}
return this;
}
public Node last() {
if(this.next == null) {
return this;
} else {
return this.next.last();
}
}
public String toString() {
String out = value+" ";
if(this.next != null) {
out += this.next.toString();
}
return out;
}
public static void main(String...arg) {
Node list = (new Node(3)).add(6).add(5).add(9);
System.out.println(list.toString());
//Output:3 6 5 9
System.out.println(list.last().toString());
//Output:9
System.out.println(list.last().prev.prev.toString());
//Output:6 5 9
}
}
You can use following DoubleLinkedList class.
public class DoubleLinkedList<T>
{
Node<T> start;
Node<T> end;
public void AddFirst(T dataToAdd)
{
Node<T> tmp = new Node<T>(dataToAdd);
if (start == null)
{
start = tmp;
end = start;
return;
}
start.previous = tmp;
tmp.next = start;
start = tmp;
if (start.next == null)
{
end = start;
}
}
public void AddLast(T dataToAdd)
{
if (start == null)
{
AddFirst(dataToAdd);
return;
}
Node<T> tmp = new Node<T>(dataToAdd);
end.next = tmp;
tmp.previous = end;
end = tmp;
}
public T RemoveFirst()
{
if (start == null) return default(T);
T saveVal = start.data;
start = start.next;
start.previous = null;
if (start == null) end = null;
return saveVal;
}
public T RemoveLast()
{
if (start == null) return default(T);
T saveVal = end.data;
end = end.previous;
end.next = null;
if (start == null) end = null;
return saveVal;
}
public void PrintAll()
{
Node<T> tmp = start;
while (tmp != null)
{
Console.WriteLine(tmp.data.ToString());
tmp = tmp.next;
}
}
}
And Use the following Node class
class Node<T>
{
public T data;
public Node<T> next;
public Node<T> previous;
public Node(T newData)
{
data = newData;
next = null;
previous = null;
}
}

Get data only one folder not for all folders in treeview - Blackberry

i want to show all folders(images, videos,files) with directories/files, currently only show images folder with files, but other folder are not show. I try to find solution but not found. Here is the code & its screenshot(http://postimg.org/image/wm5ypbk9d/).
FileManager.java
package com.rim.samples.device.mapactiondemo;
import net.rim.device.api.system.Bitmap;
import net.rim.device.api.system.KeypadListener;
import net.rim.device.api.ui.Field;
import net.rim.device.api.ui.Graphics;
import net.rim.device.api.ui.component.Dialog;
import net.rim.device.api.ui.component.TreeField;
import net.rim.device.api.ui.component.TreeFieldCallback;
import net.rim.device.api.ui.container.MainScreen;
public class FilesManager extends MainScreen {
FTPMessages _ftp = null;
String[] fileList;
// ..................
private final Bitmap openIcon = Bitmap.getBitmapResource("open.png");
private final Bitmap closedIcon = Bitmap.getBitmapResource("closed.png");
private final Bitmap movieIcon = Bitmap.getBitmapResource("movie.png");
private final Bitmap songIcon = Bitmap.getBitmapResource("song.png");
private final Bitmap playIcon = Bitmap.getBitmapResource("play.png");
private final Bitmap imgIcon = Bitmap.getBitmapResource("images.png");
String nodeTen;
int node10;
TreeField myTree;
String[] nodeData;
// ListField to be displayed - null - no Field displayed
// List of entries to be displayed - null or length = 0 means no entries
// protected so that another Thread can update this list....
protected ListDirectory[] _resultsList = null; // entries available for
// display
private ListDirectory _selectedEntry = null;
public FilesManager(FTPMessages ftp) {
super();
_ftp = ftp;
// Setting starting directory
try {
/*
* fileList = _ftp.list(); for (int i = 0; i < fileList.length; i++)
* { _ftp.cwd(fileList[i]); }
*/
_ftp.cwd("images");
_ftp.cwd("files");
_ftp.cwd("videos");
} catch (Exception e) {
}
this.setTitle("Server File List");
TreeCallback myCallback = new TreeCallback();
myTree = new TreeField(myCallback, Field.FOCUSABLE) {
protected boolean navigationClick(int status, int time) {
// We'll only override unvarnished navigation click behavior
if ((status & KeypadListener.STATUS_ALT) == 0
&& (status & KeypadListener.STATUS_SHIFT) == 0) {
final int node = getCurrentNode();
if (getFirstChild(node) == -1) {
// Click is on a leaf node. Do some default action or
// else fall through.
// Note: this will also detect empty folders, which
// might or
// might not be something your app has to handle
Dialog.alert("clicked " + getCookie(node));
// TODO: open player screen, etc.
return true;
}
}
return super.navigationClick(status, time);
}
};
myTree.setDefaultExpanded(false);
myTree.setRowHeight(openIcon.getHeight());
try {
node10 = myTree.addChildNode(0, _ftp.pwd());
} catch (Exception e) {
}
this.add(myTree);
refreshList();
}
private void refreshList() {
// TODO Auto-generated method stub
_resultsList = null;
String[] directory = null;
try {
directory = _ftp.list();
} catch (Exception e) {
}
if (directory != null && directory.length > 0) {
_resultsList = new ListDirectory[directory.length];
for (int i = 0; i < directory.length; i++) {
_resultsList[i] = new ListDirectory(directory[i],
ListDirectory.UNIX_SERVER);
}
}
if (_resultsList != null && _resultsList.length > 0) {
// we have some results
for (int i = 0; i < _resultsList.length; i++) {
String bb = directory[i];
String nodeFive = new String(bb);
this.myTree.addChildNode(node10, nodeFive);
}
} else {
}
}
private class TreeCallback implements TreeFieldCallback {
public void drawTreeItem(TreeField _tree, Graphics g, int node, int y,
int width, int indent) {
final int PAD = 8;
String text = (String) _tree.getCookie(node);
Bitmap icon = closedIcon;
if (text.endsWith(".mp3")) {
icon = songIcon;
} else if (text.endsWith(".avi")) {
icon = movieIcon;
} else if (text.endsWith(".png") || text.endsWith(".jpg")) {
icon = imgIcon;
} else if (_tree.getExpanded(node)) {
icon = openIcon;
}
g.drawBitmap(indent, y, icon.getWidth(), icon.getHeight(), icon, 0,
0);
// This assumes filenames all contain '.' character!
if (text.indexOf(".") > 0) {
// Leaf node, so this is a playable item (movie or song)
g.drawBitmap(_tree.getWidth() - playIcon.getWidth() - PAD, y
+ PAD, playIcon.getWidth(), playIcon.getHeight(),
playIcon, 0, 0);
}
int fontHeight = getFont().getHeight();
g.drawText(text, indent + icon.getWidth() + PAD,
y + (_tree.getRowHeight() - fontHeight) / 2);
}
}
}
The other classes that used with this code, download from that link(complete project classes)
http://remote.offroadstudios.com/files/filemanager.zip
you can also check files on server, ip:64.207.150.31:21, username:remote, password:123456789

Resources