How to delete the first node in a linked list? - java

I know this is a silly question, but I'm having a hard time deleting the first node in a linked list, even though the algorithm works when it's not the first node.
public boolean eliminarInscripcion(int DNI)
{
boolean flag=false;
Nodo aux, aux2; //Nodo=Node
if(Raiz!=null) //If the list isn't empty
{
aux=Raiz; //Raiz=Root
if(aux.getInfo().getDni() == DNI) //Is the first node the one i'm looking for?
{
aux.setProx(aux.getProx()); //Here is the main problem. (I've tried many things, this is one of them, looks silly anyway.)
flag=true;
}
else
{
aux2=aux.getProx(); //getProx=getNext
while(aux.getProx()!=null)
{
if (aux2.getInfo().getDni()==DNI)
{
aux.setProx(aux2.getProx());
flag=true;
break;
}
else
{
aux=aux.getProx();
aux2=aux2.getProx();
}
}
}
}
return flag;
}
Oh, and thank you very much!
Edit: I'll add some more information: the List class only has 1 atribute that is a Nodo (Raiz), the nodo class is this one:
public class Nodo
{
private Inscripcion Info;
private Nodo Prox;
public Nodo()
{
Info = null;
Prox = null;
}
public Nodo(Inscripcion info, Nodo prox)
{
this.Info = new Inscripcion(info);
this.Prox = prox;
}
public Inscripcion getInfo()
{
return Info;
}
public void setInfo(Inscripcion I)
{
this.Info = new Inscripcion(I);
}
public Nodo getProx()
{
return Prox;
}
public void setProx(Nodo P)
{
this.Prox = P;
}
#Override
public String toString()
{
return Info.toString();
}
}
Inscripcion is another class with a lot of data, I don't think itt's going to be useful here.

In a linked list, you have have a pointer to the first node and a pointer to the last node. You would do the following in (pseudo code)
LinkedList list = myList
Node node = list.head // get head
list.head = node.next // set new head to the second node in the list
node.next = null // remove the reference to the next node from the old head
You might also have to reassign the tail.
If you post your linked list class, we can help you further.

Solved it!
if(aux.getInfo().getDni() == DNI)
{
Raiz=aux.getProx();
flag=true;
}
That's how I delete the first node in my list!, thanks everybody for your questions/answers!

Related

Queue ADT using linked list Java

Using Java, I am trying to write a Queue ADT using a circular linked list (I believe I used the correct terminology, feel free to correct me if I am wrong!). The problem is that when I try to call the front method in the Queue class, it returns a NullPointerException error.
class Node
{
private Object item;
private Node next;
public Node(Object newItem) {
item = newItem;
next = null;
} // end constructor
public Node(Object newItem, Node nextNode) {
item = newItem;
next = nextNode;
} // end constructor
public void setItem(Object newItem) {
item = newItem;
} // end setItem
public Object getItem() {
return item;
} // end getItem
public void setNext(Node nextNode) {
next = nextNode;
} // end setNext
public Node getNext() {
return next;
} // end getNext
} // end class Node
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
public class Queue {
protected Node lastNode;
Queue(){
lastNode = null;
}//End default constructor
public boolean isEmpty() {
return (lastNode == null);
}//End isEmpty
public void dequeueAll() {
//Deletes the full queue since the pointer goes nowhere
lastNode = null;
}
public void enqueue(Object item) {
Node newNode = new Node(item);
if ( isEmpty() )
lastNode = newNode;
else
lastNode.setNext(newNode);
}
public void dequeue() {
if ( !(isEmpty()) )
lastNode.setNext(lastNode.getNext().getNext());
else
throw new QueueException("QueueException on dequeue:" + "queue empty");
}
public Object front() {
if ( !(isEmpty()) ) {
Node firstNode = lastNode.getNext();
return (firstNode.getItem());
}
else {
throw new QueueException("QueueException on front:" + "queue empty");
}
}
}
Here is my attempt (Node class being used is included at the top).
I believe my problem lies within the enqueue method as I do not think I am linking the list correctly. I've tried looking for a similar idea elsewhere but I haven't found many examples that I could follow in Java. If anyone could give me some pointers, I would highly appreciate it. Thanks!
public boolean isEmpty() {
return (lastNode == null);
}//End isEmpty
This method checks if the lastNode == null . However,
Node firstNode = lastNode.getNext();
If lastNode is not NULL , lastNode.getNext() can be NULL.You should check that before calling lastNode.getNext().

Need guidance on creating Node class (java)?

I need to implement a Node class, where the basic methods are: getItem(), getNext(), setItem() and setNext(). I want the nodes to be able to store at least the default integer range in Java as the “item”; the “next” should be a reference or pointer to the next Node in a linked list, or the special Node NIL if this is the last node in the list.I also want to implement a two-argument constructor which initializes instances with the given item (first argument) and next node (second argument) , I've kind of hit a brick wall and need some guidance about implementing this , any ideas ?
I have this so far:
class Node {
public Node(Object o, Node n) {
}
public static final Node NIL = new Node(Node.NIL, Node.NIL);
public Object getItem() {
return null;
}
public Node getNext() {
return null;
}
public void setItem(Object o) {
}
public void setNext(Node n) {
}
}
While implementing the custom LinkedList/Tree, we need Node. Here is demo of creating Node and LinkedList. I have not put in all the logic. Just basic skeleton is here and you can then add more on yourself.
I can give you a quick hint on how to do that:
Class Node{
//these are private class attributes, you need getter and setter to alter them.
private int item;
private Node nextNode;
//this is a constructor with a parameter
public Node(int item)
{
this.item = item;
this.nextNode = null;
}
// a setter for your item
public void setItem(int newItem)
{
this.item = newItem;
}
// this is a getter for your item
public int getItem()
{
return this.item;
}
}
You can create a Node object by calling:
Node newNode = Node(2);
This is not a complete solution for your problem, the two parameter constructor and the last node link are missing, but this should lead you in the correct direction.
Below is a simple example of the Node implementation, (i renamed Item to Value for readability purpose). It has to be implemented somehow like this, because methods signatures seems to be imposed to you. But keep in mind that this is definely not the best way to implement a LinkedList.
public class Node {
public static final Node NIL = null;
private Integer value;
private Integer next;
public Node(Integer value, Node next) {
this.value = value;
this.next = next;
}
public Integer getValue() {
return this.value;
}
public Node getNext() {
return this.next;
}
public void setValue(Integer value) {
this.value = value;
}
public void setNext(Node next) {
this.next = next;
}
public boolean isLastNode() {
return this.next == Node.NIL || Node;
}
}
public class App {
public static void main(String[] args) {
Node lastNode = new Node(92, Node.NIL);
Node secondNode = new Node(64, lastNode);
Node firstNode = new Node(42, secondNode);
Node iterator = firstNode;
do () {
System.out.println("node value : " + iterator.getValue());
iterator = iterator.getNext();
} while (iterator == null || !iterator.isLastNode());
}
}
The node class that will be implemented changes according to the linked list you want to implement. If the linked list you are going to implement is circular, then you could just do the following:
public class Node {
int data;
Node next = null;
public Node(int data){
this.data = data;
}
}
Then how are you going to implement the next node?
You are going to do it in the add method of the circularLinkedList class. You can do it as follows:
import java.util.*;
public class CircularLinkedList {
public CircularLinkedList() {}
public Node head = null;
public Node tail = null;
public void add(int data) {
Node newNode = new Node(data);
if(head == null) {
head = newNode;
}
else {
tail.next = newNode;
}
tail = newNode;
tail.next = head;
}
public void displayList() {
System.out.println("Nodes of the circular linked list: ");
Node current = head;
if(head == null) {
System.out.println("Empty list...");
}
else {
do {
System.out.print(" " + current.data);
current = current.next;
}while(current != head);
System.out.println();
}
}
}

MergeSorting LinkedList in Java recursively

So the task is to implement a linked-list and merge-sort which sorts linked-lists. I am fully aware that in industry I most likely won't have to implement any of these but I feel it's a good way to practice Java. Here is what I've got up to this point:
Node class:
public class Node<E extends Comparable<E>>
{
public E data;
public Node<E> next;
public Node(E data)
{
this.data = data;
next = null;
}
public void printData()
{
System.out.print(data + " ");
}
}
LinkedList class:
public class LinkedList<E extends Comparable<E>>
{
protected Node<E> root;
protected int size = 0;
public LinkedList()
{
root = null;
}
public void addBeg(E e)
{
Node<E> newNode = new Node<E>(e);
newNode.next = root;
root = newNode;
size++;
}
public Node deleteBeg()
{
Node<E> temp = root;
if(!isEmpty())
{
root = root.next;
size--;
}
return temp;
}
public void setRoot(Node<E> newRoot)
{
root = newRoot;
}
public boolean isEmpty()
{
return root == null;
}
public Node<E> getRoot()
{
return root;
}
public void printList()
{
Node<E> cur = root;
while(cur!=null)
{
cur.printData();
cur=cur.next;
}
System.out.println();
}
}
MergeSorter Class:
public class MergeSorter<E extends Comparable<E>>
{
public MergeSorter()
{
}
private void split(LinkedList<E> list, LinkedList<E> firHalf, LinkedList<E> secHalf)
{
//if 0 or only 1 elements in the list - it doesn't seem to work, however
if(list.getRoot() == null || list.getRoot().next == null)firHalf = list;
else{
Node<E> slow = list.getRoot();
Node<E> fast = list.getRoot().next;
while(fast!=null)
{
fast = fast.next;
if(fast!=null)
{
fast = fast.next;
slow = slow.next;
}
}
//If I use the following line firHalf list is empty when in the caller of this method (it's not in this method, however). Don't understand why ):
//firHalf = list;
firHalf.setRoot(list.getRoot());
secHalf.setRoot(slow.next);
slow.next = null;
}
}
private LinkedList<E> merge(LinkedList<E> a, LinkedList<E> b)
{
LinkedList<E> mergedList = new LinkedList<E>();
Node<E> dummy = new Node<E>(null);
Node<E> tail = dummy;
while(true)
{
if(a.getRoot() == null){
tail.next = b.getRoot();
break;
}
else if(b.getRoot() == null){
tail.next = a.getRoot();
break;
}
else
{
if(a.getRoot().data.compareTo(b.getRoot().data) <= 0)
{
tail.next = a.getRoot();
tail = tail.next;
a.setRoot(a.getRoot().next);
}
else
{
tail.next = b.getRoot();
tail = tail.next;
b.setRoot(b.getRoot().next);
}
tail.next = null;
}
}
mergedList.setRoot(dummy.next);
return mergedList;
}
public void mergeSort(LinkedList<E> list)
{
Node<E> root = list.getRoot();
LinkedList<E> left = new LinkedList<E>();
LinkedList<E> right = new LinkedList<E>();
if(root == null || root.next == null) return; //base case
split(list, left, right); //split
mergeSort(left);
mergeSort(right);
list = merge(left, right); // when this mergeSort returns this list should be
// referenced by the left or right variable of the
// current mergeSort call (but it isn't!)
}
}
I am fairly new to Java (coming from a C background) so I am sincerely sorry in advance if my code is utterly false. When I test the split and merge methods in the MergeSorter class independently, everything seems to work (splitting a list consisting of 0 or 1 element is not working and is driving me crazy but this is not needed for merge-sorting). The mergeSort method, however, is not working and I can't seem to figure out way. I tried to debug it myself and there's seems to be a problem when two halves are merged into one list and then the recursion returns. The newly merged list should be referenced by either the left or right variable of the current mergeSort call but instead I get only the last element instead of the whole list.
Method arguments in Java are always passed by value.
This can be a bit confusing, since objects are always accessed via references, so you might think they're passed by reference; but they're not. Rather, the references are passed by value.
What this means is, a method like this:
public void methodThatDoesNothing(Object dst, Object src) {
src = dst;
}
actually does nothing. It modifies its local variable src to refer to the same object as the local variable dst, but those are just local variables that disappear when the function returns. They're completely separate from whatever variables or expressions were passed into the method.
So, in your code, this:
firHalf = list;
does not really do anything. I guess what you want is:
while (! firHalf.isEmpty()) {
firHalf.deleteBeg();
}
if (! list.isEmpty()) {
firHalf.addBeg(list.root().data);
}
which modifies the objected referred to by firHalf so it has the same zero-or-one elements as list.

how to Implement the add and member methods of the SetImpl.java?

Everyone. Anyone can help me how to start this question. I am not very clear about it. Very appreciate.
The question is:
Implement the add and member methods of the SetImpl.java. Note that it is strongly recommended that you do not allow duplicates during add - that would make other methods more challenging to implement.
The following is the java coding about SetImpl.java:
import java.util.List;
import java.util.ArrayList;
import java.util.Iterator;
public class SetImpl<T> implements Set<T>{
// container class for linked list nodes
private class Node<T>{
public T val;
public Node<T> next;
}
private Node<T> root; // empty set to begin with
// no need for constructor
// add new element to the set by checking for membership.. if not
// then add to the front of the list
public void add(T val){
}
// delete element from the list - may be multiple copies.
public void delete(T val){
}
// membership test of list
public boolean member(T val){
return false;
}
// converts to a list
public List<T> toList(){
ArrayList<T> res;
return res;
}
// does simple set union
public void union(Set<T> s){
}
}
Anyone can give me some tips about this question?
Thanks very much!
First try
private Node < T > root = null;
private Node < T > head = null;
private Node < T > tail = null;
public void add(T val) {
if (head == null) {
head = tail = new Node < T > ();
head.val = val;
root.next = tail;
tail = head;
} else {
tail.next = new Node < T > ();
tail = tail.next;
tail.val = val;
}
}
Okay here is just hints on how you should go in your logic :
public class SetImpl<T> implements Set<T>{
// container class for linked list nodes
///// It is said "Linked list" --> first hint google that
private class Node<T>{
public T val;
public Node<T> next;
}
private Node<T> root; // empty set to begin with
///// So that's my "root" which means I will have descendants
// no need for constructor
// add new element to the set by checking for membership.. if not
// then add to the front of the list
// Basically here everything is said.
// 1- check membership
// 2- if true do nothing (as it has been said, it's a Set, if you don't know why I say that google Set Collections
//if false (which means the val I want to add is not in my set) then I can add it to the Set
public void add(T val){
}
// delete element from the list - may be multiple copies.
public void delete(T val){
}
// membership test of list
// that's recursive calls. How do you check that? where do you store your values?
// It's true if your current Node.val attribute == the value OR if the rest of the Nodes has the value as member. Here you really need to know about Linked List
public boolean member(T val){
return false;
}
// converts to a list
public List<T> toList(){
ArrayList<T> res;
return res;
}
// does simple set union
public void union(Set<T> s){
}
}
Your implementation
private Node < T > root = null;
private Node < T > head = null;
private Node < T > tail = null;
public void add(T val) {
if (head == null) {
head = tail = new Node < T > ();
head.val = val;
root.next = tail;
tail = head;
} else {
tail.next = new Node < T > ();
tail = tail.next;
tail.val = val;
}
}
My guess is you don't need to add fields in such exercises. It's already half baked for you. Check out how linked list works. I'm lazy so I provide first "linked list" result from google. :)
Have fun

Doubly linked lists

I have an assignment that I am terribly lost on involving doubly linked lists (note, we are supposed to create it from scratch, not using built-in API's). The program is supposed to keep track of credit cards basically. My professor wants us to use doubly-linked lists to accomplish this. The problem is, the book does not go into detail on the subject (doesn't even show pseudo code involving doubly linked lists), it merely describes what a doubly linked list is and then talks with pictures and no code in a small paragraph. But anyway, I'm done complaining. I understand perfectly well how to create a node class and how it works. The problem is how do I use the nodes to create the list? Here is what I have so far.
public class CardInfo
{
private String name;
private String cardVendor;
private String dateOpened;
private double lastBalance;
private int accountStatus;
private final int MAX_NAME_LENGTH = 25;
private final int MAX_VENDOR_LENGTH = 15;
CardInfo()
{
}
CardInfo(String n, String v, String d, double b, int s)
{
setName(n);
setCardVendor(v);
setDateOpened(d);
setLastBalance(b);
setAccountStatus(s);
}
public String getName()
{
return name;
}
public String getCardVendor()
{
return cardVendor;
}
public String getDateOpened()
{
return dateOpened;
}
public double getLastBalance()
{
return lastBalance;
}
public int getAccountStatus()
{
return accountStatus;
}
public void setName(String n)
{
if (n.length() > MAX_NAME_LENGTH)
throw new IllegalArgumentException("Too Many Characters");
else
name = n;
}
public void setCardVendor(String v)
{
if (v.length() > MAX_VENDOR_LENGTH)
throw new IllegalArgumentException("Too Many Characters");
else
cardVendor = v;
}
public void setDateOpened(String d)
{
dateOpened = d;
}
public void setLastBalance(double b)
{
lastBalance = b;
}
public void setAccountStatus(int s)
{
accountStatus = s;
}
public String toString()
{
return String.format("%-25s %-15s $%-s %-s %-s",
name, cardVendor, lastBalance, dateOpened, accountStatus);
}
}
public class CardInfoNode
{
CardInfo thisCard;
CardInfoNode next;
CardInfoNode prev;
CardInfoNode()
{
}
public void setCardInfo(CardInfo info)
{
thisCard.setName(info.getName());
thisCard.setCardVendor(info.getCardVendor());
thisCard.setLastBalance(info.getLastBalance());
thisCard.setDateOpened(info.getDateOpened());
thisCard.setAccountStatus(info.getAccountStatus());
}
public CardInfo getInfo()
{
return thisCard;
}
public void setNext(CardInfoNode node)
{
next = node;
}
public void setPrev(CardInfoNode node)
{
prev = node;
}
public CardInfoNode getNext()
{
return next;
}
public CardInfoNode getPrev()
{
return prev;
}
}
public class CardList
{
CardInfoNode head;
CardInfoNode current;
CardInfoNode tail;
CardList()
{
head = current = tail = null;
}
public void insertCardInfo(CardInfo info)
{
if(head == null)
{
head = new CardInfoNode();
head.setCardInfo(info);
head.setNext(tail);
tail.setPrev(node) // here lies the problem. tail must be set to something
// to make it doubly-linked. but tail is null since it's
// and end point of the list.
}
}
}
Here is the assignment itself if it helps to clarify what is required and more importantly, the parts I'm not understanding. Thanks
https://docs.google.com/open?id=0B3vVwsO0eQRaQlRSZG95eXlPcVE
if(head == null)
{
head = new CardInfoNode();
head.setCardInfo(info);
head.setNext(tail);
tail.setPrev(node) // here lies the problem. tail must be set to something
// to make it doubly-linked. but tail is null since it's
// and end point of the list.
}
the above code is for when u not have any nodes in list, here u r going to add nodes to ur list.I.e. ist node to list
here u r pointing head & tail to same node
I assume CardList is meant to encapsulate the actual doubly-linked-list implementation.
Consider the base case of a DLL with only a single node: the node's prev and next references will be null (or itself). The list's encapsulation's head and tail references will both be the single node (as the node is both the start and end of the list). What's so difficult to understand about that?
NB: Assuming that CardList is an encapsulation of the DLL structure (rather than an operation) there's no reason for it to have a CardInfoNode current field, as that kind of state information is only useful to algorithms that work on the structure, which would be maintaining that themselves (it also makes your class thread-unsafe).

Categories