Guys I am a newbie and i am learning data structures.I am learning Linked list implementation of stack and I wrote this code below for the implementation.
the push method works fine but the pop method doesnt works fine and doesnt deletes the node.
public class Slink {
Node head;
public void push(int data)
{
Node node =new Node();
node.data=data;
node.next=null;
if(head==null)
{
head=node;
}
else
{
Node n=head;
while (n.next!=null)
{
n=n.next;
}
n.next=node;
}
}
public void pop()
{
if(head==null)
{
System.out.println("Stack has 0 items .. cant delete");
}
else {
Node n = head;
while (n.next != null) {
n = n.next;
}
n=null;
}
}
public void show()
{
Node n=head;
while(n.next!=null)
{
System.out.println(n.data);
n=n.next;
}
System.out.println(n.data);
}
}
Now using this in a class.
public class Sll {
public static void main(String[] args) {
Slink stk=new Slink();
stk.push(4);
stk.push(54);
stk.push(23);
stk.push(90);
stk.pop();
stk.show();
}
}
The output is
4
54
23
90
while 90 should have been removed.
Guys please tell me where i am wrong and correct me.
Thanks
n=null; in your pop() method modifies nothing else than the value of your scoped n variable. You will instead want to set n.next=null on the last node which has a non-null next.
It can be done in the following way for example :
public void pop()
{
if(head==null)
{
System.out.println("Stack has 0 items .. cant delete");
}
else if(head.next == null) {
head = null;
}
else {
Node n = head;
while (n.next != null && n.next.next != null) {
n = n.next;
}
n.next=null;
}
}
You can try it here. (I've also fixed your show() method to work correctly with empty stacks)
In pop method instead of:
Node n = head;
while (n.next != null) {
n = n.next;
}
n=null;
Try:
head = head.next();
Actually, you did not mention your node(), class. It seems that you didn't make tail node which is necessary for the link list.
I think this code will definitely help you
Pop() method
public void pop() {
node current = header;
node back = null;
while ((current != null)) {
if ((current == tail)) {
back.next = null;
tail = back;
break;
}
else {
back = current;
current = current.next;
}
Node Class
class node {
public int data;
public node next;
public node(int data) {
this.data = this.data;
this.next = null;
}
}
Do some changes in Push method
public void push(int data) {
node nnew = new node(data);
if ((header == null)) {
header = nnew;
tail = nnew;
}
else {
tail.next = nnew;
tail = tail.next;
}
}
Related
I created my own Linked List using nodes, and I have few methods to do.
Methods in main:
//List<Person> females = peopleFromWarsaw.getWithFilter(p -> p.getName().endsWith("a"));
// Dont know how to implements this methods.
// ObjectContainer.removeIf(p -> p.getAge() > 50);
// peopleFromWarsaw.storeToFile("youngPeopleFromWarsaw.txt",
// p -> p.getAge() < 30, p -> p.getName() + ";" + p.getAge() + ";" + p.getCity());
At the begging i made a linked list and tried to print elements from list but doesnt work.
At first it looks like it doesn't have a method toString but class Person has toString. I guess the program takes the node but I want to print object.
Maybe u can see what is the problem with code, basically nodes and methods in Object Container are fine.
Secondly i have a problem with implementing methods in main (getWithFilter,removeIf and storeToFile)
No matter how I write method in ObjectContainer, always intelij tells me that cannot use lambda and underline p.getName (p -> p.getName().endsWith("a"));
In class Person i have getters and setters with fields name,age.
Maybe someone could explain how properly write this methods ?
public class ObjectContainer<T> {
private Node head;
private Node tail;
private final Predicate<T> predicate;
public ObjectContainer(Predicate<T> predicate) {
this.predicate = predicate;
}
static class Node {
private Object object;
private Node next;
Node(Object object) {
this.object = object;
}
}
public void add(T object) {
if (!predicate.test(object)) {
throw new IllegalArgumentException("Element can not be added");
}
Node newNode = new Node(object);
if (head == null) {
head = newNode;
tail = newNode;
} else {
tail.next = newNode;
tail = newNode;
}
}
public int size() {
int count = 0;
Node current = head;
while (current != null) {
count++;
current = current.next;
}
return count;
}
public void push(T new_data) {
Node new_node = new Node(new_data);
new_node.next = head;
head = new_node;
}
public void insertAfter(Node prev_node, T new_data) {
if (prev_node == null) {
System.out.println("The given previous node cannot be null");
return;
}
Node new_node = new Node(new_data);
new_node.next = prev_node.next;
prev_node.next = new_node;
}
public void append(T new_data) {
Node new_node = new Node(new_data);
if (head == null) {
head = new Node(new_data);
return;
}
new_node.next = null;
Node last = head;
while (last.next != null)
last = last.next;
last.next = new_node;
return;
}
public void printList() {
Node tnode = head;
while (tnode != null) {
tnode = tnode.next;
System.out.println(tnode);
}
}
}
Probably you don't want to print the node, but the object contained within. Also, you want to print the first object, too. That is
public void printList() {
Node tnode = head;
while (tnode != null) {
System.out.println(tnode.object);
tnode = tnode.next;
}
}
I am trying to implement stack but pop() in not working properly. The last element after popping doesn't get deleted and stack does not get empty. I have checked the head at last does not points to null which is causing the problem. I am not able to find why this is happening can anyone please explain.
public class StackUsingLL {
public class Node{
int data;
Node next;
Node(int data){
this.data=data;
}
}
Node head;
boolean isEmpty() {
if(head==null)return true;
return false;
}
void push(int x) {
Node newNode= new Node(x);
if(head==null) {
head=newNode;
}
newNode.next=head;
head=newNode;
}
int pop() {
if(head==null) {
System.out.println("Stack is empty");
return 0;
}else {
int popped=head.data;
head= head.next;
return popped;
}
}
int peek() {
if(head==null) {
System.out.println("Stack empty");
return 0;
}
return head.data;
}
public static void main(String[] args) {
StackUsingLL sll= new StackUsingLL();
sll.push(10);
sll.push(20);
sll.push(30);
System.out.println(sll.pop()+" popped");
System.out.println(sll.pop()+" popped");
System.out.println(sll.pop()+" popped");
System.out.println(sll.isEmpty());
System.out.println("at top: "+sll.peek());
}
}
The issue is in push. When the list is empty you assign head twice:
void push(int x) {
Node newNode = new Node(x);
if (head == null) {
head = newNode;
return; // <<--- Add this so it doesn't get assigned in the following lines.
}
newNode.next = head;
head = newNode;
}
Without the return you end up with head.next = head.
I recommend that just don't change the reference head but also delete it . By just changing the reference , prev Node is still intact
int pop() {
if(head==null) {
System.out.println("Stack is empty");
return 0;
}
Node popped=head;
head=head.next;
popped.next=null;
return popped.data;
}
I'm trying to write a method to insert a node and remove a node at the back of a linked list. Here's the main class I'm writing the methods in. They're at the bottom (insertBack and removeBack):
public class LinkedList
{
private LinkedListNode head;
public LinkedList()
{
head = null;
}
public LinkedListNode getHead()
{
return head;
}
public void setHead(LinkedListNode h)
{
head = h;
}
public void insertFront(Object item)
{
if (head == null)
{
LinkedListNode nextNode = new LinkedListNode (item);
head = nextNode;
}
else
{
LinkedListNode nextNode = new LinkedListNode (item);
nextNode.setNext(head);
head = nextNode;
}
}
public Object removeFront()
{
if (head == null)
{
return head;
}
else
{
LinkedListNode t = head;
Object ret = head.getData();
head = head.getNext();
t.setNext(null);
t = null;
return ret;
}
}
//insert a front at the end of linked list
public void insertBack(Object myData)
{
LinkedListNode newNode = new LinkedListNode(myData);
if (head == null)
{
head = newNode;
}
else
{
LinkedListNode current = head;
while (current.getNext() != null)
{
current = current.getNext();
}
current.setNext(newNode);
}
}
//remove a node at the end of linked list
public Object removeBack()
{
if (head == null)
{
return null;
}
if (head.getNext() == null)
{
return null;
}
LinkedListNode secondToLast = head;
while (secondToLast.getNext().getNext() != null)
{
secondToLast = secondToLast.getNext();
}
secondToLast.setNext(null);
return head.getData();
}
}
There's probably formatting errors as I pasted this here, but I'm still trying to figure out how to use this site. When I run my driver class, shown below, I get the results shown below that.
public static void main(String[] args)
{
ValueData data1 = new ValueData("a", 50);
ValueData data2 = new ValueData("b", 70);
ValueData data3 = new ValueData("c", 100);
LinkedList myList = new LinkedList();
//practice insertBack and removeBack
myList.insertBack(data1);
myList.insertBack(data2);
myList.insertBack(data3);
System.out.println("Test insertBack and removeBack");
System.out.println((ValueData) myList.removeBack());
System.out.println((ValueData) myList.removeBack());
System.out.println((ValueData) myList.removeBack());
System.out.println();
//compare insertFront and removeFront
System.out.println("Test insertFront and removeFront");
myList.insertFront(data1);
myList.insertFront(data2);
myList.insertFront(data3);
System.out.println((ValueData)myList.removeFront());
System.out.println((ValueData)myList.removeFront());
System.out.println((ValueData)myList.removeFront());
System.out.println();
RESULTS
Test insertBack and removeBack
a 50.0
a 50.0
null
Test insertFront and removeFront
c 100.0
b 70.0
a 50.0
Can anyone help me figure out why my removeFront and removeBack methods are not working?
First of all this code is unnecessary, as an object that has no reference will just be thrown away.
t.setNext(null);
t = null;
This also may help removeBack()
if(head == null) {
return null;
}
LindedListNode current = head;
while(current.getNext() != null) //searching for last node
current = current.getNext();
current = null; //make the last node null
public class LinkedList<T>
{
private Node head;
private int size;
public LinkedList()
{
}
public void addToHead(T value) // create new node, make new node point to head, and head point to new node
{
if (head == null)
{
head = new Node(value,null);
}
else
{
Node newNode = new Node(value,head);
head = newNode;
}
size++;
}
public boolean isEmpty()
{
return head == null;
}
public int size()
{
return size;
}
public void removeHead()
{
head = head.next;
size--;
}
public void addToTail(T value)
{
if (isEmpty())
{
System.out.println("You cannot addtoTail of a emptyList!");
}
else
{
System.out.println(value);
Node current = head;
System.out.println("we are pointing to head: "+current);
while (current.getNext() != null) // loop till the end of the list (find the last node)
{
System.out.println("we are now pointing to: "+current.getElement());
current = current.getNext();
}
System.out.println("We are at the last node:"+current); // its working
System.out.println("it should point to null:"+current.getNext()); // its working
current.setNext(new Node(value,null)); // make it point to our new node we want to insert
System.out.println(current.getNext()); // it is pointing to the new node.. yet the node is not actually inserted (local variable problem? )
size++;
}
}
public String toString()
{
String output = "";
if (!isEmpty())
{
Node current = head;
output = "";
while (current.getNext() != null)
{
output += current.toString()+ "->";
current = current.getNext();
}
}
return output;
}
protected class Node
{
private T element;
private Node next;
public Node()
{
this(null,null);
}
public Node(T value, Node n)
{
element = value;
next = n;
}
public T getElement()
{
return element;
}
public Node getNext()
{
return next;
}
public void setElement(T newElement)
{
element = newElement;
}
public void setNext(Node newNext)
{
next = newNext;
}
public String toString()
{
return ""+element;
}
}
}
So I have written this linkedlist class, and every method works except addtoTail. For example say I create a instance of my linkedlist class, and call addToHead(5), then addtoTail(6) and use my toString method to print out the linkedlist, it only contains 5->. I debugged the addToTail and everything seems to be pointing to the correct locations, yet for some reason it does not add the new node (6) to the list. Hopefully I explained that clearly. I am probably missing something really simple (I even drew it on paper to visualize it but do not see the problem).
Your addToTail function is probably fine. I think the culprit is your toString function. In particular, in this snippet:
while (current.getNext() != null)
{
output += current.toString()+ "->";
current = current.getNext();
}
Your condition terminates the loop before reaching the end. What you actually want is:
while(current != null) {
....
}
Hey ya'll I am having a little trouble with my singly linked list. I decided to create a simple one because we do not get enough practice during my data structures class and cannot seem to find why I am not getting the right output.
The code is:
package linked_list;
public class LinkedList {
private Node head;
private Node tail; // After figuring out head, come back to this FIXME
private int listSize;
public LinkedList() {
head = new Node(null);
tail = new Node(null);
}
public void addLast(String s) {
Node newNode = new Node(s);
if (head == null) {
addFirst(s);
} else {
while (head.next != null) {
head = head.next;
}
head.next = newNode;
tail = newNode;
}
listSize++;
}
public void addFirst(String s) {
Node newNode = new Node(s);
if (head == null) {
head = newNode;
tail = newNode;
}
else {
newNode.next = head;
head = newNode;
}
listSize++;
}
public Object getFirst() {
return head.data;
}
public Object getLast() {
return tail.data;
}
public void clear() {
head = null;
tail = null;
listSize = 0;
}
public Object peek() {
try {
if (head == null) {
throw new Exception ("The value is null");
}
else {
return head;
}
} catch (Exception e) {
System.out.println(e.getMessage());
return null;
}
}
public int size() {
return listSize;
}
// This class has the ability to create the nodes that are used
// in the Linked List.
private class Node {
Node next;
Object data;
public Node(String value) {
next = null;
data = value;
}
public Node(Object value, Node nextValue) {
next = nextValue;
data = value;
}
public Object getData() {
return data;
}
public void setData(Object dataValue) {
data = dataValue;
}
public Node getNext() {
return next;
}
public void setNext(Node nextValue) {
next = nextValue;
}
}
}
Now here is my driver that I created to run a simple little operation:
package linked_list;
public class LinkedListDriver {
public static void main(String[] args) {
LinkedList list1 = new LinkedList();
list1.clear();
list1.addLast("This goes last");
list1.addFirst("This goes first");
list1.addLast("Now this one goes last");
System.out.println(list1.getFirst());
System.out.println(list1.getLast());
}
}
My output is this:
This goes last
Now this one goes last
I guess my question is why am I not getting the answer This goes first from my getFirst() method. It seems to be something wrong with the order or structure of that method but I cannot pinpoint it.
When you are in the else in the addLast, you are changing the reference to head. You should use another reference pointer to traverse the list when adding in the else.
Also, your list size should only be incremented in the else in addLast because you are incrementing twice otherwise (once in addFirst and again after the if-else in addLast).