So I was wondering how I could create a new empty linked list, using my class definition of List and node, with a first head node pointing to null without having to hold any integer value. The thing is I'm not allowed to change the given methods or add any to the definition, so whenever I create a list, in the constructor I'm not sure how I'm supposed to asign head to null. Here's part of the codes:
public class Node {
private Node next;
private int key;
Node(Node nxt, int keyValue) {
key = keyValue;
next = nxt;
}
Node getNext() {
return next;
}
int getKey() {
return key;
}
void putNext(Node nxt) {
next = nxt;
}
}
Class List
public class List {
private Node head;
List() {
head = new Node(null, -1); // arbitary value for head
head.putNext(null);
}
This is what I came up with. I just assign a random value to variable key in head node. But if I do this, it will kinda mess up with my later methods that used recursive like deletion or finding sum or find max, min, etc Is there any other way around I can do to deal with this issue?
java.util.LinkedList
for some ideas. There should be a lot of similarities between what you're doing for your class assignment and how this class works. – Kreasehead = null
? Heck, that's the default value forhead
anyway... (You don't have to - you certainly can use a sentinel value for the head of the list, but I'm not sure I'd bother in this case.) – Jon Skeethead = null;
is the perfect thing to place in your constructor. also your callhead.putNext(null);
in your constructor is superfluous since your constructor setsnext
tonull
, you will be doing the same thing twice! – Nathan McCoy