Linked Lists With No Imports
I'm trying to create a linked list, either double or开发者_高级运维 single without using any imports, it's part of a class project. but what i'm not understanding i guess is how to actually create and add an item to the list, without using java.util. I have
public boolean insertItem( ItemType newItem)
{
if( p==0 || m==MAX_LENGTH)
{
head.elem = elem;
head.next = tail;
tail = head;
return false;
}
else
{
tail.next = new ListNode(); //adds new node to the end of the list
tail = tail.next;//set the tail pointer to that node
tail.elem = newItem; //set elem to be stored to the end node
m++;
return true;
}
}
so i'd love some input on why this doesn't work. and how i actually create this list, i've been using an array just Object list[] = new list[MAX_LENGTH]
but i'm not sure if that's the right way to go about it.
I'd start with something like:
class LinkedList
{
static class Node
{
ItemType item;
Node next;
Node prev; // if making a doubly linked list
}
private Node head;
private Node tail; // if making a doubly linked list
public boolean insertItem(ItemType item)
{
// make a new Node
// check for the head to be null...
// add the node to the end of the list, or make the head/tail point at it.
}
}
And no, it's the wrong way to go.
See Wikipedia: Linked List -- that's the data-structure that this assignment calls for. Each cell has a value and a "pointer" to the next (and possibly previous).
Do not use arrays -- the list structure is self-contained in the cells and links.
Consider this signature to add a new item: (Once the basic operation is understood/implemented, this can be trivially folded back into a method.)
static LinkedList insert(LinkedList item, LinkedList newItem) {
// Update item to "point to" newItem and have newItem "point to" where
// item used to "point to". Return the new "head" of this
// segment.
// Notes:
// `item` may be null to "insert at start of empty list"
// This function should be *static* and should only modify
// item and newItem.
}
Usage cases:
LinkedList head = insert(null, new LinkedList("a"));
insert(head, new LinkedList("b"));
length(head); // should be 2, cons cells should look like `("a", ("b", null))`
insert(head, new LinkedList("c"));
length(head); // should be 3, cons cells should look like `("a", ("c", ("b", null)))`
Remember that LinkedList
object above refers to a single "cell" with two (or three) members: "the value", "next" (and optionally, "prev"). Depending upon preference, etc., Node
or Cell
may be a more suitable name to leave LinkedList
to refer to the standard collection and/or outside container.
Happy homeworking.
Note: The LinkedList
in the Java collection API is a container which uses a linked-list as an underlying implementation. As such, it misses out of a number of nice use-cases of linked-lists often employed in functional-ish programming languages.
精彩评论