0
votes

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?

1
Take a look at the implementation of 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.Krease
Can you not just use head = null? Heck, that's the default value for head 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 Skeet
@jon is right! head = null; is the perfect thing to place in your constructor. also your call head.putNext(null); in your constructor is superfluous since your constructor sets next to null, you will be doing the same thing twice!Nathan McCoy
Chris: in the constructor, it doesnt specify how it creates an empty list so I still cant figure out how.VictorN
yeah thanks guys head = null should be working for now. That is i need to change all my codes according to that. I'll try work that out and see if anything else comes upVictorN

1 Answers

0
votes

In an Empty Linked List Head is Just a pointer which points to Nothing. You dont need to worry about creating an object to which current head points. Just create a head pointer and assign it to NULL. When you are actually adding a Node assign the address of first node to Head. Thats it...

public class List {
    private Node *head;
    List() {
       head = NULL; 
    }
}