queue implementation does not return first element - java

I want to emulate a queue by using linked lists in Java. My general schema is to have a list of nodes, with two nodes that points to the first and last element of my queue. When I perform the dequeue() I want to get ride of the first element. So far what I have done is the following:
public class Node {
public Object e;
Node next;
public Node(Object e) {
this.e = e;
}
}
public class Queue {
Node queueList;
Node first, last;
int count;
public void enQueue(Object n) {
Node temp = new Node(n);
temp.next = last;
last = temp;
if (queueList == null) {
first = temp;
}
count++;
queueList=temp;
}
public Object deQueue() {
Node previous = last;
Node current = last.next;
Object num = null;
if (count == 0)
System.out.println("empty queue");
else {
while (current.next != null) {
previous = previous.next;
current = current.next;
}
num = first.e;
first = previous;
count--;
}
return num;
}
public void print() {
Node current = last;
while (current != null) {
System.out.println(current.e);
current = current.next;
}
}
}
I do not want to use double linked lists, so for the dequeue() operation what I do is to traverse my list with two pointers like this:
So when the current.next points to a null, I want that previous to be the first node. The problem that I got is when I print the elements of my queue it stills prints me: 10,15,5,18, but the 18 value is not deleted. Any help?
Thanks

There are basically two things I would correct in your code.
First of all, the Queue field was not assigned any value, and I also doubt its utility, basically its logic can be applied using first
public void enQueue(Object n) {
Node temp = new Node(n);
temp.next = last;
last = temp;
if (first == null) { <--- HERE
first = temp;
}
count++;
}
The second one is that you never put the value of the new head of the queue next to null which is needed in that case
public Object deQueue() {
Node previous = last;
Node current = last.next;
Object num = null;
if (count == 0) System.out.println("empty queue");
else {
while (current.next != null) {
previous = previous.next;
current = current.next;
}
num = first.e;
first = previous;
first.next = null; <--- HERE
count--;
}
return num;
}

Related

How to sort a linked list using priority queue

I have been trying to write a method to take in a linked list and sort it using a priority queue
I have no clue how to write this code I understand how a priority queue is supposed to work but I don't know how to put that into code
Override
public void priorityEnqueue(AnyType x) {
if (isEmpty()){
back = front = new ListNode<>(x);
}
{
back=back.next = new ListNode<>(x);
}
}
I am aware of the fact that this only returns the list as is without sorting it and that is exactly what I need help with
This is the answer I figured it out
#Override
public void priorityEnqueue(AnyType x) {
ListNode<AnyType> node = new ListNode<>(x);
if(front == null){
front = node;
back = node;
}
else{
if(front.element.compareTo(x) > 0){
node.next = front;
front = node;
}
else{
ListNode<AnyType> current = front;
while(current.next != null && current.next.element.compareTo(x) < 0)
current = current.next;
node.next = current.next;
current.next = node;
if(node.next == null)
back = node;
}
}
}

How can I get my next pointer of my LinkedList class without using built in function?

I'm newbie in programming and I'm practicing a Java Programming Language. I was having a rough day in finding the solution of my program because I cannot get my "next" pointer and I really want to print my last value. Could someone help me to fix this and explain to me? Thank you in advance. Here's my code.
Note: The output of my program is 5.
public class Node {
private int data;
private Node next;
public Node (int data){
this.data = data;
}
public int getData() {
return this.data;
}
public void setNext(Node n) {
this.next = n;
}
public Node getNext() {
return this.next;
}
}
public class LinkedList {
private static Node head, next;
public LinkedList (int data) {
head = new Node (data);
}
public void addLast(int data) {
Node n = new Node (data);
if (head == null) {
head = n;
}
else {
Node temp = head;
temp.setNext(next);
while (temp.getNext() != null) {
temp = temp.getNext();
}
Node t = temp.getNext();
t = n;
}
}
public void printList() {
head.setNext(next);
while (head.getNext() != null) {
System.out.println(head.getData());
head = head.getNext();
}
System.out.println(head.getData());
}
public static void main(String[] args) {
LinkedList l = new LinkedList(5);
l.addLast(7);
l.printList();
}
}
I suggest following two amendment to your code.
with following else block in addLast method.
Node temp = head;
temp.setNext(next); // this line causing the next object to be set to null all the time. commenting this line will help in making sure the follwing loop reaches to end of the list, otherwise the while loop will always exit without any iteration.
while (temp.getNext() != null) {
temp = temp.getNext();
}
Node t = temp.getNext();
t = n; // this will also not change the linking. Its basically assigned a new value to t.
use following suggestion
Node temp = head;
while (temp.getNext() != null) {
temp = temp.getNext();
}
// now we reached end of list and temp.next is null.
// assign newly createdd node to temp.next
temp.setNext(n);
While iterating the element in printList same problem exist as mentioned in point 1. try to use following suggestion for printList method.
// head.setNext(next); // This line will always set head.next to null and whole list will be lost. Instead of this use following line
Node temp = head;
while (temp.getNext() != null) { // here if you use head its position will move to end. So use temp variable for iteration
System.out.println(temp.getData());
temp= temp.getNext();
}
System.out.println(temp.getData());
You may also need to study list iteration algorithm to have better understanding.
I've made some amendments to make your code work. The If statement in your addLast method:
if (head == null) {
is redundant since your LinkedList can only be initialized by passing some data, hence head will never be null, it will always point to the Node containing data
Also the line
head.setNext(next);
in your printList() was problematic, it was always pointing to null
public class LinkedList {
private static Node head, next;
public LinkedList(int data) {
head = new Node(data);
}
public void addLast(int data) {
Node n = new Node(data);
Node temp = head;
temp.setNext(next);
while (temp.getNext() != null) {
temp = temp.getNext();
}
temp.setNext(n);
}
public void printList() {
while (head.getNext() != null) {
System.out.println(head.getData());
head = head.getNext();
}
System.out.println(head.getData());
}
public static void main(String[] args) {
LinkedList l = new LinkedList(5);
l.addLast(7);
l.printList();
}
}
TL;DR:
You set null as the next node in your printList() method;
Your addLast does not work either (you do not set the next node (see details below);
You should never set the node (or do any logical alteration whatsoever) in your print method. Print must just print, as the name suggests, and it should not contain any side-effect, amending your data structure. That is: you have to clearly separate your concerns.
In your current addLast, you do:
public void addLast(int data) {
Node n = new Node (data);
if (head == null) {
head = n;
}
else {
Node temp = head;
temp.setNext(next);
while (temp.getNext() != null) {
temp = temp.getNext();
}
Node t = temp.getNext();
t = n;
}
}
which means, that when your temp's next node is null, you never add the Node you instantiate with your int argument.
Change the else block as follows:
else {
Node temp = head;
temp.setNext(next);
while (temp.getNext() != null) {
temp = temp.getNext();
}
temp.setNext(n);
//two redundant lines removed
}
Correspondingly, remove head.setNext(next); (and possibly unnecessary System.out.println() statement) from your printList() method.
P. S. I would really recommend you to spend some time on the Linked List Data Structure (Data Structure, and not the Java code), as your current design, shows that you need to have a better grasp of it.

I have a problem in the reference of my 'head' node in my own LinkedList Class

I had written my own Linked Class Codes with Node first and last, since there exists a Node last, I encountered problems regarding reference and pointer manipulations when I tried to manually created the LinkedList in the main method and test it.
I am quite familiar with the recursion implemented in the "addFirst" "addLast" and "remove" methods, but now somehow the reference to the Node first becomes null after addFirst Method.
public class LinkedList<T> {
Node first,last,temp;
public class Node{
T value;
Node next;
public Node(T value, Node next) {
this.value = value;
this.next = next;
}
public String toString(){
if(next == null){
return value.toString();
}
else{
return value.toString() + " " + next.toString();
}
}
public T getLL(int index){
if(index == 0){
return value;
}
if(next == null){
throw new
IndexOutOfBoundsException("have reached the end of the list, none found");
}
return next.getLL(index-1);
}
public T removeLL(int x){
if(x == 1){
T value = next.value;
next = next.next;
return value;
}
else if(next == null){
throw new
IndexOutOfBoundsException("have reached the end of the list, none found");
}
else{
return next.removeLL(x-1);
}
}
}
public LinkedList(T value) {
temp = new Node(value,null);
first = new Node(value,null);
last = temp;
}
public static void main(String[] args) {
/**
* [120,110,100,90,80];
*/
LinkedList L = new LinkedList(100);
L.addFirst(110);
L.addFirst(120);
L.addLast(90);
L.addLast(80);
System.out.println(L.size());
System.out.println(L.remove(0));
System.out.println(L.last.toString());
//return null which causes the remove method not to work.
System.out.println(L.first);
}
public void addFirst(T value){
first = new Node(value,first);
}
public void addLast(T value){
Node p = first;
if( p == null){
first = last = new Node(value,null);
}
while(p.next!= null){
p = p.next;
}
last.next = new Node(value,null);
last = new Node(value,null);
}
public T get(int index){
if(first == null){
throw new IndexOutOfBoundsException("empty list");
}
return first.getLL(index);
}
public int size(){
int c = 0;
while(first != null){
first = first.next;
c++;
}
return c;
}
public T remove(int x){
if(first == null){
throw new IndexOutOfBoundsException("Tried to remove from empty list");
}
if (x == 0) {
T value = first.value;
first = first.next;
return value;
}
return first.removeLL(x);
}
}
I expected that the Node first pointed to the first element of the LinkedList instead of pointing to null. Meanwhile, this won't affect the pointer of Node last.
Looks like the problem inside the AddLast function. You braking the list.
Shouldn't it be like this?
public void addLast(T value){
Node p = first;
if( p == null){
first = last = new Node(value,null);
}
while(p.next!= null){
p = p.next;
}
p.next = new Node(value,null);
last = p.next;
//last = new Node(value,null);
}
Update Regarding your comment and updated answer.
Your size function is wrong:
public int size(){
int c = 0;
while(first != null){
first = first.next; // <-- now first point to the last and length is 1
c++;
}
return c;
}
When you remove the first element first is null. You have to create temporary variable to traverse your list. To check this comment the line where you calculate size.
Your are actually not quite right last.next = new Node(value,null); point to the new node. But instead of connecting again last = last.next your new node is gone because you create your new node for the last but last.next pointed to new node and hence last is not last anymore. (I think your understood what I meant)

Writing a method to sort a singly linkedlist in ascending order (java)

the method 'insertAscending' only gives me the first number even after i enter new ones. can anyone help with what i'm doing wrong? Thanks.
public class LinkedList13 {
// Private inner class Node
private class Node{
int data;
Node link;
public Node(){
data = Integer.MIN_VALUE;
link = null;
}
public Node(int x, Node p){
data = x;
link = p;
}
}
// End of Node class
public Node head;
public LinkedList13(){
head = null;
}
public void insertAscending(int data){
Node node = new Node();
node.data = data;
if (head == null)
head = node;
Node p = head;
while (p.link != null)
{
if (p.link.data > data)
{ node.link = p.link;
p.link = node;
break;
}
p= p.link;
}
}
}
Hint: is (p.link != null) ever true?
First of all, you should return after setting the head of the list (when the first element is added).
Second of all, you should handle the case where the newly inserted node is the smallest in the list (and therefore should come first). Your loop never compares the added node to the head of the list.
Finally, if the added element wasn't inserted in the while loop, it should be inserted after the while loop.
public void insertAscending(int data)
{
Node node = new Node();
node.data = data;
if (head == null) {
head = node;
return;
} else if (node.data < head.data) {
node.link = head;
head = node;
return;
}
Node p = head;
boolean added=false;
while (p.link != null)
{
if (p.link.data > data)
{
node.link = p.link;
p.link = node;
added = true;
break;
}
p = p.link;
}
if (!added)
p.link = node;
}
Check out your if condition if(p.link.data > data) the only way a node gets into the list is when that is true. This means, that, if the value of data being inserted it greater than (or equal to) everything that's been inserted so far, it will be discarded.
An easy way to fix this is change break to return and add p.link=node at the end (after the loop).

Single linked list in java

In the following code, I am trying to understand one thing in the insertFirst() method that
Why is the last statement first =newLink; and not first.next=new Link;
Will it be wrong? Isn't there a "next" in first?
I know this code is right and I know that a node needs to be inserted at the beginning and all, but I need help understanding just one statement.
Is first =newLink; and first.next=new Link; not the same thing?
public class LinkedList {
private Link first;
public LinkedList()
{
first = null;
}
public boolean isEmtpy()
{
return(first==null);
}
public void insertFirst(int id, int dd)
{
Link newLink=new Link(id,dd);
newLink.next=first;
first =newLink;
}
}
No, it's right: the list inserts new links at the beginning. The old "first" becomes the new link's "next", and the new link is the new "first".
Why is the last statement first =newLink; and not first.next=new Link;
Because you're inserting a new first element and the "next" element is the old first element, which was set on the previous line.
Is first =newLink; and first.next=new Link; not the same thing?
No. first is the first and first.next is the second.
This is because you want to put new element to the beginning, so you must set new element to the head of list and this element should point on "old-head", and then you have:
new_elemnt->old_head->...
LinkedList::first is not a guard element. It really points to the first element of the list. If LinkedList::first == null, then the list is empty. If Link::next == null, then it's the last element (the null is called a guard element in this case).
Simple example of SingleLinkedList in Java
package com.ds;
public class SingleLinkedList {
private Node head;
public static void main(String[] args) {
SingleLinkedList linkedList = new SingleLinkedList();
linkedList.insert(5);
linkedList.insert(15);
linkedList.insert(45);
linkedList.insert(55);
linkedList.insert(58);
linkedList.insert(25);
// Print value of Single Linked list.
linkedList.print();
// delete node from tail side.
linkedList.delete();
linkedList.delete();
linkedList.delete();
linkedList.delete();
linkedList.delete();
/*linkedList.delete();
linkedList.delete();
linkedList.delete();
linkedList.delete();*/
linkedList.print();
}
SingleLinkedList() {
head = null;
}
void insert(int val) {
Node temp = new Node();
temp.data = val;
temp.next = null;
if (head == null) {
head = temp;
} else {
Node k = head;
while (k.next != null) {
k = k.next;
}
k.next = temp;
}
}
// delete from tail.
void delete() {
// if it's first node
if (head == null || head.next == null) {
head = null;
} else {
Node n = head;
Node t = head;
while (n.next != null) {
t = n;
n = n.next;
}
t.next = null;
}
}
void print() {
Node k = head;
while (k != null) {
System.out.println(k.data);
k = k.next;
}
}
Node reverse() {
Node h = head;
Node p = null;
Node t = null;
while (h != null) {
t = h.next;
h.next = p;
p = h;
h = t;
}
return p;
}
class Node {
private int data;
private Node next;
}
}

Categories

Resources