Sorry for a noob question, but the syntax is a bit confusing here. I am asked to fill in the function to insert new element onto the front of a linked list. The code:
class LinkedList
{
public LinkedList ()
{
this.head = null;
}
/* returns true, if the list is empty, else false */
public boolean isEmpty ()
{
return head == null;
}
/* returns the first element of the list, assuming that the list is not empty */
public int front ()
{
return head.data;
}
/* prints the list */
public void print ()
{
System.out.print("(");
for (ListNode i = head; i != null; i = i.next)
System.out.print(i.data + " ");
System.out.println(")");
}
/* inserts x into the beginning of the list */
public void insertFront (int x)
{
/* FILL HERE!!! */
}
}
The code for the nodes:
class ListNode
{
public ListNode()
{
this.data = 0;
this.next = null;
}
public int data;
public ListNode next;
}
I figured I need to create a new node, assign the value of the current head for the next operator, and set the value equal to x. And then finally set the node to be the new head.
Can someone show me how to perform those basic commands.
Just declare your new element as head and let it point to the previous head, which is now the second element.
/* inserts x into the beginning of the list */
public void insertFront(int x)
{
// Temporarily memorize previous head
ListNode previousHead = this.head;
// Create the new head element
ListNode nextHead = new ListNode();
nextHead.data = x;
// Let it point to the previous element which is now the second element
nextHead.next = previousHead;
// Update the head reference to the new head
this.head = nextHead;
}
Here is a small illustration of the process:
Related
I am trying to implement the set method where you pass in the position in a linked list that you want and the value and the set function adds that value into the position specified in the linked list. I have implemented the set function but for some reason The last element disappears in my implementation. I would greatly appreciate any help. Thanks in advance. I would appreciate any expert eyes that will see what I am missing.
/**
* A basic singly linked list implementation.
*/
public class SinglyLinkedList<E> implements Cloneable, Iterable<E>, List<E> {
//---------------- nested Node class ----------------
/**
* Node of a singly linked list, which stores a reference to its
* element and to the subsequent node in the list (or null if this
* is the last node).
*/
private static class Node<E> {
E value;
Node<E> next;
public Node(E e)
{
value = e;
next = null;
}
}
//----------- end of nested Node class -----------
// instance variables of the SinglyLinkedList
private Node<E> head = null; // head node of the list (or null if empty)
private int size = 0; // number of nodes in the list
public SinglyLinkedList() {
} // constructs an initially empty list
// access methods
/**
* Returns the number of elements in the linked list.
*
* #return number of elements in the linked list
*/
public int size() {
return size;
}
/**
* Adds an element to the end of the list.
*
* #param e the new element to add
*/
public void addLast(E e) {
// TODO
}
/**
* Tests whether the linked list is empty.
*
* #return true if the linked list is empty, false otherwise
*/
public boolean isEmpty() {
return size == 0;
}
#Override
public E get(int i) throws IndexOutOfBoundsException {
Node<E> a = head;
if(i<=this.size()) {
int count = 0;
while(count < i) {
count ++;
a = a.next;
}
return a.value;
}
return null;
}
#Override
public E set(int i, E e) throws IndexOutOfBoundsException {
Node<E> current = head;
Node<E> setNode = new Node<E>(e);
if(i==0) {
this.addFirst(e);
}
else if(i==this.size){
this.addLast(e);
}
else {
for(int j=0; current != null && j < (i-1);j++) {
current = current.next;
}
Node<E> temp = current.next;
current.next = setNode;
setNode.next = temp;
}
return setNode.value;
}
// update methods
/**
* Adds an element to the front of the list.
*
* #param e the new element to add
*/
public void addFirst(E e) {
Node<E> first = new Node<>(e);
first.next = this.head;
this.head = first;
this.size++;
}
#SuppressWarnings({"unchecked"})
public boolean equals(Object o) {
// TODO
return false; // if we reach this, everything matched successfully
}
#SuppressWarnings({"unchecked"})
public SinglyLinkedList<E> clone() throws CloneNotSupportedException {
// TODO
return null;
}
/**
* Produces a string representation of the contents of the list.
* This exists for debugging purposes only.
* #return
*/
public String toString() {
for(int i=0;i<this.size();i++) {
System.out.println(this.get(i));
}
return "end of Linked List";
}
public static void main(String[] args) {
SinglyLinkedList <Integer> ll =new SinglyLinkedList <Integer>();
ll.addFirst(5);
ll.addFirst(4);
ll.addFirst(3);
ll.addFirst(2);
ll.set(1,0);
System.out.println(ll);
}
}
Assumptions
addLast method is missing in the code
The error could be there too
Known cause
This code is not incrementing the size inside the set method's for loop.The size is incremented in addLast(possibly) and addFirst and not incremented in other case (final else part)
It is not clear what is planned to do with set method. The way it is implemented now, it behaves more like insert, meaning that it will add new node, bit it does not increase the total count of elements (size).
It the set method is changing the value of the node, which name indicates, then this part is wrong:
else {
for(int j=0; current != null && j < (i-1);j++) {
current = current.next;
}
Node<E> temp = current.next;
current.next = setNode;
setNode.next = temp;
}
It should replace the value instead of adding the new one:
else {
for(int j=0; current != null && j < (i-1);j++) {
current = current.next;
}
current.value=e
}
Also, it looks like the index i is 1-based, while everything else is 0 based. I didn't check the code above, but the concept should be like shown.
I have two custom made doubly linked list and a method insertAt(int pos,DoublyLinkedList l) that should insert the list l before the given index of the other list. However, after using it, nothing happens, even though when I watch the proccess in debugger everything seems to go fine. Program compiles, it just does not give any result. Here's the minimal example:
public class DoublyLinkedList{
private static final class Node {
protected Object data;
protected Node next, prev;
/* Constructor */
public Node() {
next = null;
prev = null;
data = 0;
}
/* Constructor */
public Node(Object d, Node n, Node p) {
data = d;
next = n;
prev = p;
}
/* Function to set link to next node */
public void setLinkNext(Node n) {
next = n;
}
/* Function to set link to previous node */
public void setLinkPrev(Node p) {
prev = p;
}
/* Funtion to get link to next node */
public Node getLinkNext() {
return next;
}
/* Function to get link to previous node */
public Node getLinkPrev() {
return prev;
}
/* Function to set data to node */
public void setData(Object d) {
data = d;
}
/* Function to get data from node */
public Object getData() {
return data;
}
}
protected Node start;
protected Node end;
public int size;
/* Constructor */
public DoublyLinkedList() {
start = null;
end = null;
size = 0;
}
public void insertBefore(int pos, DoublyLinkedList l) {
Node ptr = start;
if (pos == 1) {
l.end.setLinkNext(start);
start.setLinkPrev(l.end);
} else {
for (int i = 2; i <= size; i++) {
if(i==pos){
ptr.setLinkPrev(l.end);
l.end.setLinkNext(ptr);
Node tmp=ptr;
ptr = ptr.getLinkPrev();
ptr.setLinkNext(l.start);
l.start.setLinkNext(tmp);
size=size()+l.size();
break;
}
ptr=ptr.getLinkNext();
}
}
}
public static void main(String[] args) {
// TODO code application logic here
DoublyLinkedList list1 = new DoublyLinkedList();
list1.insertAtEnd("a");
list1.insertAtEnd("b");
list1.insertAtEnd("c");
list1.insertAtEnd("d");
list1.insertAtEnd("e");
DoublyLinkedList list2 = new DoublyLinkedList();
list2.insertAtEnd("1");
list2.insertAtEnd("2");
list2.insertAtEnd("3");
list2.insertAtEnd("4");
list2.insertAtEnd("5");
list1.display();
list2.display();
list1.insertBefore(3, list2);
list1.display();
list1.size();
}
}
Any help will be appreciated
Look at this part of your code:
ptr.setLinkPrev(l.end);
l.end.setLinkNext(ptr);
Node tmp=ptr;
ptr = ptr.getLinkPrev();
ptr.setLinkNext(l.start);
l.start.setLinkNext(tmp);
it sets the end of the new list as ptr's predecessor, and links it back properly.
a temporary variable keeps the current reference to ptr.
Then you move ptr to refer to its predecessor. But this predecessor is not what used to be ptr's predecessor in the original list. It's the result of step (1) above, the end item of the new list!
Then you tell this item, the end of the new list, to link to the new list's beginning... The new list will now become a circle. But only singly-linked.
Then you link the start's next to what you saved - the old ptr.
As a result your forward links from the old start still go the old way - they have not changed much. But the back links are broken, and the new list's links are broken.
You think nothing changed because your printing method probably just walks the list through its forward links. Try to write another printing method that walks them backwards, it should become interesting...
One way to solve this would be to save ptr's predecessor before you replace it, and use that for forward-linking the new list.
The problem is here:
ptr.setLinkPrev(l.end);
l.end.setLinkNext(ptr);
Node tmp=ptr;
ptr = ptr.getLinkPrev();
//ptr is now the last node of l, not the previous node of original list!!!
//==> you cycle your l list again in the next instruction:
ptr.setLinkNext(l.start);
l.start.setLinkNext(tmp);
size=size()+l.size();
break;
You should save the previous node of ptr BEFORE you start merging...
It should be:
Node tmp = prev.getLinkPrev();
ptr.setLinkPrev(l.end);
l.end.setLinkNext(ptr);
tmp.setLinkNext(l.start);
l.start.setLinkPrev(tmp);
size=size()+l.size();
break;
I figured this out with help of your hint guys, thanks.
public void insertBefore(int pos, DoublyLinkedList l) {
checkOutOfBounds(pos);
Node ptr = start;
if (pos == 1) {
l.end.setLinkNext(start);
start.setLinkPrev(l.end);
start=l.start;
size=size()+l.size();
} else {
for (int i = 2; i <= size; i++) {
if(i==pos){
Node tmp=ptr;
ptr.setLinkPrev(l.end);
l.end.setLinkNext(ptr.getLinkNext());
tmp.setLinkNext(l.start);
l.start.setLinkPrev(tmp);
size=size()+l.size();
break;
}
ptr=ptr.getLinkNext();
}
}
}
Having a bit of trouble adding a node to the end of my linked list. It only seems to display the very last one I added before I call my addFirst method. To me it looks like on the addLast method I'm trying to first create the node to assign it 5, then for the following numbers use a while loop to assign them to the last node on the linked list. Little stuck on why I can't get my output to display 5 and 6.
class LinkedList
{
private class Node
{
private Node link;
private int x;
}
//----------------------------------
private Node first = null;
//----------------------------------
public void addFirst(int d)
{
Node newNode = new Node();
newNode.x = d;
newNode.link = first;
first = newNode;
}
//----------------------------------
public void addLast(int d)
{
first = new Node();
if (first == null)
{
first = first.link;
}
Node newLast = new Node();
while (first.link != null)
{
first = first.link;
}
newLast.x = d;
first.link = newLast;
first = newLast;
}
//----------------------------------
public void traverse()
{
Node p = first;
while (p != null)
{
System.out.println(p.x);
p = p.link;
}
}
}
//==============================================
class test123
{
public static void main(String[] args)
{
LinkedList list = new LinkedList();
list.addLast(5);
list.addLast(6);
list.addLast(7);
list.addFirst(1);
list.addFirst(2);
list.addFirst(3);
System.out.println("Numbers on list");
list.traverse();
}
}
I've also tried creating a last Node and in the traverse method using a separate loop to traverse the last node. I end up with the same output!
public void addLast(int d)
{
Node newLast = new Node();
while (last.link != null)
{
last = newLast.link;
}
newLast.x = d;
newLast.link = last;
last = newLast;
}
The logic of your addLast method was wrong. Your method was reassigning first with every call the logic falls apart from that point forward. This method will create the Node for last and if the list is empty simply assign first to the new node last. If first is not null it will traverse the list until it finds a Node with a null link and make the assignment for that Nodes link.
public void addLast(int d) {
Node last = new Node();
last.x = d;
Node node = first;
if (first == null) {
first = last;
} else {
while (node.link != null) {
node = node.link;
}
node.link = last;
}
}
Your addLast() method displays the value of the last node because every time you append a node to the end of your list, you are overwriting the reference to "first". You are also doing this when you assign a new reference to first in the following line:
first = new Node();
Try the following:
public void addLast(int d)
{
Node newLast = new Node();
if (first == null)
{
newLast.x = d;
first = newLast;
return;
}
Node curr = first;
while (curr.link != null)
{
curr = curr.link;
}
newLast.x = d;
curr.link = newLast;
}
The method creates a new node and it is added to the end of the list after checking two conditions:
1.) If first is null: in this case the list is empty and the first node should be
initialized to the new node you are creating, then it will return (or you could do
an if-else).
2.) If first is not null: If the list is not empty you'll loop through your list until you
end up with a reference to the last node, after which you will set its next node to the
one you just created.
If you wanted to keep track of the tail of your list called "last", like you mentioned above, then add:
last = newLast
at the end of your method. Hope this helps!
This is a homework assignment and im just stomped. Can anyone tell me what i am doing wrong?
I am trying to make a copy of a linked List but it says the new list is null.
I try debugging the code with appropriate prints, 1 printing the current node's data to be copyed, and the second to print the newList's last linked node to make sure it is being linked. They seem to be printing the right info, but the list is still null.
run:
h1 is 123456789
Expected: h1 is 123456789
1
2
tail digit:1
3
tail digit:2
4
tail digit:3
5
tail digit:4
6
tail digit:5
7
tail digit:6
8
tail digit:7
9
tail digit:8
h3 is null
Expected: h3 is 123456789
BUILD SUCCESSFUL (total time: 0 seconds)
UPDATE:
I did some further testing with this, and its actually not null and print the correct data,
if(newList.head != null || newList != null)
{
System.out.println ("not null :D");
System.out.println(newList.toString());
}
so that means h3 != newList that i made in the constructor. how do i set it so
HugeNumber h3 = new HugeNumber(h1);
h3 = newList throught the constructor.
public static void main(String[] args)
{
// Create a HugeNumber that is 123456789
HugeNumber h1 = new HugeNumber();
for (int i=9; i>=1; i--)
{
h1.addDigit(i);
}
System.out.println("h1 is " + h1.toString());
System.out.println("Expected: h1 is 123456789");
// Make a copy of h1
HugeNumber h3 = new HugeNumber(h1);
System.out.println("h3 is " + h3.toString());
System.out.println("Expected: h3 is 123456789");
}
class HugeNumber
{
/**
* Inner class to store a digit within a node
*/
private class DigitNode
{
private int digit=0; // Value for this digit
private DigitNode next=null; // Reference to next digit
private DigitNode prev=null; // Reference to previous digit
/**
* DigitNode constructor, initializes number
*/
public DigitNode(int d)
{
digit = d;
}
/* Accessor and mutator methods */
public int getDigit()
{
return digit;
}
public void setDigit(int d)
{
digit = d;
}
public DigitNode getNext()
{
return next;
}
public void setNext(DigitNode nextNode)
{
next = nextNode;
}
public DigitNode getPrev()
{
return prev;
}
public void setPrev(DigitNode prevNode)
{
prev = prevNode;
}
}
// Variable declarations
private DigitNode head = null; // Head points to the most significant digit in the list
private DigitNode tail = null; // Tail points to the least significant digit in the list
/**
* Constructors
*/
public HugeNumber()
{
}
/**
* addDigit adds a new digit, d, as a new most significant
* digit for the list.
* #param d new digit to add as the MSD
*/
public void addDigit(int d)
{
DigitNode nodes = new DigitNode(d);
if (head != null)
{
head.setPrev(nodes);
nodes.setNext(head);
}
head = nodes;
if(tail == null)
{
tail = nodes;
}
}
/**
* Resets the HugeNumber to a null, empty value
*/
public void resetValue()
{
head = null;
tail = null;
}
/**
* #return String The HugeNumber converted to a string
*/
public String toString() {
if (head == null)
{
return null;
}
String print = "";
DigitNode temp = head;
while (temp != null) {
print = print + temp.getDigit();
temp = temp.getNext();
}
return print;
}
/**
* Deep copy constructor
* #param newVal Input HugeNumber to copy to this HugeNumber
*/
This constructor is where i make a copy of it.
public HugeNumber(HugeNumber newVal)
{
// Traverse the input HugeNumber, copying each node to a new list
//
HugeNumber newList = new HugeNumber ();
newList.head = newVal.head;
newList.tail = newList.head;
DigitNode currentNode = new DigitNode(1);
DigitNode OldListNode = newVal.head;
//to make sure the head is copied
System.out.println(newList.head.digit);
while(currentNode != newVal.tail)
{
OldListNode = OldListNode.next;
currentNode = OldListNode;
//to make sure the currentNode is the one we want to copy and it is being transverse
System.out.println(currentNode.digit);
currentNode.setPrev(newList.tail);
newList.tail.setNext(currentNode);
newList.tail = currentNode;
// to make sure the list is linked
System.out.println("tail digit:" + newList.tail.prev.digit);
}
if(newList.head == null || newList == null )
{
System.out.println("--------------------------newList is null :(");
}
}
}
You just create new local variable newList in the constructor method to hold the data, and it will not exist after the invocation of constructor method. You should use this key word
The problem is in your overloaded constructor where you are creating a new object , which is unnecessary. You dont need to explicitly create an object there.The object will be created for you and you can access that using this reference.
Here is your modified constructor.
public HugeNumber(HugeNumber newVal) {
// Traverse the input HugeNumber, copying each node to a new list
//
//HugeNumber this = new HugeNumber();
this();
this.head = newVal.head;
this.tail = this.head;
DigitNode currentNode = new DigitNode(1);
DigitNode OldListNode = newVal.head;
// to make sure the head is copied
System.out.println(this.head.digit);
while (currentNode != newVal.tail) {
OldListNode = OldListNode.next;
currentNode = OldListNode;
// to make sure the currentNode is the one we want to copy and it is
// being transverse
System.out.println(currentNode.digit);
currentNode.setPrev(this.tail);
this.tail.setNext(currentNode);
this.tail = currentNode;
// to make sure the list is linked
System.out.println("tail digit:" + this.tail.prev.digit);
}
if (this.head == null || this == null) {
System.out.println("--------------------------newList is null :(");
}
}
hello im trying to implement a Linked list in java.
As this is a homework assignment I am not allowed to use the built in LinkedList from java.
Currently I have implemented my Node class
public class WordNode
{
private String word;
private int freq;
private WordNode next;
/**
* Constructor for objects of class WordNode
*/
public WordNode(String word, WordNode next )
{
this.word = word;
this.next = next;
freq = 1;
}
/**
* Constructor for objects of class WordNode
*/
public WordNode(String word)
{
this(word, null);
}
/**
*
*/
public String getWord()
{
return word;
}
/**
*
*/
public int getFreq(String word)
{
return freq;
}
/**
*
*/
public WordNode getNext()
{
return next;
}
/**
*
*/
public void setNext(WordNode n)
{
next = n;
}
/**
*
*/
public void increment()
{
freq++;
}
}
and my "LinkedList"
public class Dictionary
{
private WordNode Link;
private int size;
/**
* Constructor for objects of class Dictionary
*/
public Dictionary(String L)
{
Link = new WordNode(L);
size = 1;
}
/**
* Return true if the list is empty, otherwise false
*
*
* #return
*/
public boolean isEmpty()
{
return Link == null;
}
/**
* Return the length of the list
*
*
* #return
*/
public int getSize()
{
return size;
}
/**
* Add a word to the list if it isn't already present. Otherwise
* increase the frequency of the occurrence of the word.
* #param word The word to add to the dictionary.
*/
public void add(String word)
{
Link.setNext(new WordNode(word, Link.getNext()) );
size++;
}
Im having trouble with implementing my add method correctly, as it has to check the list, for wether the word allready exists and if do not exists, add it to the list and store it alphabetic.
Ive been working on a while loop, but cant seem to get it to work.
Edit: Ive been trying to print the list but it wont print more than the first added word
public void print()
{
WordNode wn = Link;
int size = 0;
while(wn != null && size <= getSize()){
System.out.println(wn.getWord()+","+wn.getFreq(wn.getWord()));
size++;
}
}
Any help is appreciated
Your add method is wrong. You're taking the root node and setting its next value to the new node. So you will never have any more than 2 nodes. And if you ever have 0, it will probably crash due to a null pointer.
What you want to do is set a current value to the root node, then continue getting the next node until that node is null. Then set the node.
WordNode current = Link;
// Check if there's no root node
if (current == null) {
Link = new WordNode(word);
} else {
// Now that the edge case is gone, move to the rest of the list
while (current.getNext() != null) {
/* Additional checking of the current node would go here... */
current = current.getNext();
}
// At the last element, at then new word to the end of this node
current.setNext(new WordNode(word));
}
You need to keep the instance of the previous node so you can set the next value. Since this would cause a problem if there are no nodes to begin with, there needs to be some extra logic to handle a root node differently. If you'll never have 0 nodes, then you can remove that portion.
If you also need to check the values of the variables in order to see if it's there, you can add something to the while loop that looks at the current value and sees if it is equal to the current word you're looking for.
WordNode current = Link;
while (current != null) {
//check stuff on current word
current = current.getNext();
}
Without your loop code, it will be hard to help you with your specific problem. However, just to give you a bit of a hint, based on the instructions you don't actually have to search every node to find the word. This will give you the opportunity to optimize your code a bit because as soon as you hit a word that should come after the current word alphabetically, then you can stop looking and add the word to the list immediately before the current word.
For instance, if the word you're adding is "badger" and your words list are
apple-->avocado-->beehive-->...
You know that beehive should come after badger so you don't have to keep looking. What you will need to implement is a method that can do alphabetical comparison letter-by-letter, but I'll leave that to you ;-)
Assuming that you always insert in alphabetical order it should look something like this:
public void add(String word){
WordNode wn = Link;
WordNode prevNode = null;
while(wn != null){
if(word.equals(wn.getWord())){
//match found, increment frequency and finish
wn.increment();
return;
}else if(word.compareTo(wn.getWord) < 0){
//the word to add should come before the
//word in the current WordNode.
//Create new link for the new word,
//with current WordNode set as the next link
WordNode newNode = new WordNode(word, wn)
//Fix next link of the previous node to point
//to the new node
if(prevNode != null){
prevNode.setNext(newNode);
}else{
Link = newNode;
}
//increase list size and we are finished
size++;
return;
}else{
//try next node
prevNode = wn;
wn = wn.getNext();
}
}
//If we got here it means that the new word
//should be added to the end of the list.
WordNode newNode = new WordNode(word);
if(prevNode == null){
//if list was originally empty
Link = newNode;
}else{
//else append it to the end of existing list
prevNode.setNext(newNode);
}
//increment size and finish
size++;
}
Use this code :
class NodeClass {
static Node head;
static class Node {
int data;
Node next;
//constractor
Node(int d) {
data=d;
next=null;
}
}
static void printList(Node node ) {
System.out.println("Printing list ");
while(node!=null){
System.out.println(node.data);
node=node.next;
}
}
static void push(int data) {
Node node = new Node(data);
node.next = head;
head = node;
}
static void addInLast(int data) {
Node node = new Node(data);
Node n = head;
while(n.next!=null){
n= n.next;
}
n.next = node;
node.next = null;
}
public static void main (String[] args) {
NodeClass linklistShow = new NodeClass();
linklistShow.head = new Node(1);
Node f2 = new Node(2);
Node f3 = new Node(3);
linklistShow.head.next = f2;
f2.next =f3;
printList(linklistShow.head);
push(6);
addInLast(11);
printList(linklistShow.head);
}
}