Issues with reversing the linkedlist - java

I'm trying to learn about linked list and it has been little challenging for me. I'm trying to reverse the link list with recursive method. Here is my code:
public class ListNode {
Node head = null;
int nodeCount= 0;
int counter = 0;
ListNode(){
head = null;
}
public void insertNode( String name ) {
if (head == null) {
head = new Node(name, null);
nodeCount++;
} else {
Node temp = new Node(name, null);
temp.next = head;
head = temp;
nodeCount++;
}
}
public Node reverseTest(Node L){
// Node current = new Node(null,null);
if(L == null || L.next ==null){
return L;
}
Node remainingNode = reverseTest(L.next);
Node cur = remainingNode;
while(cur.next !=null){
cur=cur.next;
}
L.next = null;
cur.next = L;
return remainingNode;
}
public static void main(String[] args){
ListNode newList = new ListNode();
newList.insertNode("First");
newList.insertNode("Second");
newList.insertNode("Third");
newList.insertNode("Fourth");
newList.reverseTest(newList.head);
}
}
The problem I'm having with is the reverse method. When the method is over it only returns the last node with the value "First".Through the entire recursion remainingNode only holds and returs value from the base case which is confusing me. I was excepting it to move further through the nodes. After the method is executed newList holds only one node with next node as null and that node is the head now. I was assuming it will reverse the linkedlist with the sequence First --> Second--> Third --> Fourth. What am I doing wrong?

Actually, everything works here. Your only problem is in your main method: you don't get the result of your method.
newList.reverseTest(newList.head);
You need to actually set the new head with the result:
newList.head = newList.reverseTest(newList.head);
This would have been easier to see if you had declared your method static:
newList.head = ListNode.reverseTest(newList.head);
As a bonus, here is a fully recursive equivalent:
public static Node reverse(Node head) {
if (head == null || head.next == null) {
return head;
}
Node newHead = reverse(head.next);
// head.next points to the new tail, we push the former head at the end
head.next.next = head;
// now head has become the new tail, we cut the end of the list
head.next = null;
return newHead;
}

Related

When I delete from a LinkedList object vs. Deleting a node from given a head node why do I get different results?

I think I know what the problem may be (a misunderstanding on Global vs. Local variables), but would like further verification on why it is not doing what I would like it to.
So, originally, I was just messing around and tried to implement the LinkedList delete method as follows :
(Also, I know most of this looks a mess right now, I think I am doing some bad practices, so you may be frank)
// Practicing with Lists...
public class ListPrac {
/*
Implement Delete for
singly-linked linked list
*/
public static void main(String[] args) {
ListNode head = new ListNode(1);
head.next = new ListNode(2);
head.next.next = new ListNode(3);
head.next.next.next = new ListNode(4);
delete(head, 1);
System.out.println("done");
}
public static int delete(ListNode head, int deleteMe) {
ListNode temp = head;
ListNode prev = null;
// need to check if it is first and
// need to check if it is at the end...
if (temp != null && temp.dat == deleteMe) {
temp = temp.next;
return deleteMe;
}
// ^ two edge cases...
while (temp != null) {
int curVal = temp.dat;
if (curVal == deleteMe && head.dat == curVal) {
head = temp.next;
return deleteMe; // done...
}
if (curVal == deleteMe) {
if (temp.next != null) {
prev.next = temp.next;
return deleteMe; // done...
}
}
prev = temp;
temp = temp.next;
}
return -1; // not found, so not deleted...
}
public static class ListNode {
int dat;
ListNode next;
public ListNode(int val) {
dat = val;
next = null;
}
}
}
When I debug this and check what the head looks like in the end, it still shows 1->2->3->4,
but as I went through the method, it seemed to be doing the right thing for when I removed a middle element (for ex, removing 3 yields giving me 1->2->4 at the end)
When looking at geeksforgeeks they implement it like this (and it works fine)
(this is just a snippet with delete rest can be found at https://www.geeksforgeeks.org/linked-list-set-3-deleting-node/):
class LinkedList1
{
Node head; // head of list
/* Linked list Node*/
class Node
{
int data;
Node next;
Node(int d)
{
data = d;
next = null;
}
}
/* Given a key, deletes the first occurrence of key in linked list */
void deleteNode(int key)
{
// Store head node
Node temp = head, prev = null;
// If head node itself holds the key to be deleted
if (temp != null && temp.data == key)
{
head = temp.next; // Changed head
return;
}
// Search for the key to be deleted, keep track of the
// previous node as we need to change temp.next
while (temp != null && temp.data != key)
{
prev = temp;
temp = temp.next;
}
// If key was not present in linked list
if (temp == null) return;
// Unlink the node from linked list
prev.next = temp.next;
}
}
(There may be other things wrong with my code, but right now I am just focusing on removal of the first element not working)
I think the problem may be that I do not fully understand what is happening globally vs. locally if that makes sense?
For further clarification :
(Also further looking into it, I think there are a lot of differences in approach to mine vs. geeksforgeeks, but I think I narrowed down where my problem lies) Anyways, after moving some things around, I think my question is really about why their delete method works with a linked list object vs. just a linked list built using ListNodes in main, for example below :

// Practicing with Lists...
public class ListPrac1 {
public static ListNode head;
public static ListNode headExample; // the different example
public static void main(String[] args) {
ListPrac1 ll1= new ListPrac1();
ll1.push(4);
ll1.push(3);
ll1.push(2);
ll1.push(1);
ll1.delete(1);
System.out.println("done");
System.out.println("\nLinked List after Deletion of 1:");
ll1.printList();
// This is what they did basically while creating a LinkedList
// Object I guess and it works...
// but... with the same structure of delete method and just
// using ListNodes to build a list starting with
// variable headExample instead and then calling deleteMine.
// (which has the same structure as delete except a reference to
// the new head...)
ListNode headExample = new ListNode(1);
headExample.next = new ListNode(2);
headExample.next.next = new ListNode(3);
headExample.next.next.next = new ListNode(4);
deleteMine(1);
System.out.println();
System.out.println("\nLinked List starting with headExample after Deletion of 1:");
while (headExample != null) {
System.out.print(headExample.dat + " ");
headExample = headExample.next;
}
}
public static void printList() {
ListNode tnode = head;
while (tnode != null)
{
System.out.print(tnode.dat+" ");
tnode = tnode.next;
}
}
public static int delete(int deleteMe) {
// Store head node
ListNode temp = head, prev = null;
// If head node itself holds the key to be deleted
if (temp != null && temp.dat == deleteMe)
{
head = temp.next; // Changed head
return deleteMe;
}
// Search for the key to be deleted, keep track of the
// previous node as we need to change temp.next
while (temp != null && temp.dat != deleteMe)
{
prev = temp;
temp = temp.next;
}
// If key was not present in linked list
if (temp == null) return -1;
// Unlink the node from linked list
prev.next = temp.next;
return deleteMe;
}
public static int deleteMine(int deleteMe) {
// Store head node
ListNode temp = headExample, prev = null;
// If head node itself holds the key to be deleted
if (temp != null && temp.dat == deleteMe)
{
headExample = temp.next; // Changed head
return deleteMe;
}
// Search for the key to be deleted, keep track of the
// previous node as we need to change temp.next
while (temp != null && temp.dat != deleteMe)
{
prev = temp;
temp = temp.next;
}
// If key was not present in linked list
if (temp == null) return -1;
// Unlink the node from linked list
prev.next = temp.next;
return deleteMe;
}
public static void push(int new_data) {
ListNode new_node = new ListNode(new_data);
new_node.next = head;
head = new_node;
}
public static class ListNode {
int dat;
ListNode next;
public ListNode(int val) {
dat = val;
next = null;
}
}
}
Output yields :
done


Linked List after Deletion of 1:

2 3 4


Linked List starting with headExample after Deletion of 1:

1 2 3 4
So it works for their way when creating a LinkedList, but not the other way where I make one with Nodes.
The delete and deleteMine methods are the same except deleteMine references headExample (which is what builds my second list in the second part)
So, my question really is:
Shouldn’t the delete work in both cases? Since both the LinkedList and headExample reference their respective head variables, why is headExample not being modified after delete, but the LinkedList ll1 is?
I think the problem of your implementation is that you do not have a 'List'-object.
You have some instances of the ListNode class.
For a LinkedList you need to have an additional class that represents the List.
That List-class should have a ListNode variable that represents the head of the list. Look at the
class LinkedList1
{
Node head; // head of list
part. It has a member named 'head'.
When the delete method is called it changes the head member variable of the list object.
If the class ListPrac represents your list a starting point could look like this:
public class ListPrac {
// each instance of ListPrac has a ListNode that represents the head of the list.
ListNode head;
public static void main(String[] args) {
ListPrac theList = new ListPrac();
ListNode head = new ListNode(1);
head.next = new ListNode(2);
head.next.next = new ListNode(3);
head.next.next.next = new ListNode(4);
// here we assign a ListNode as the head of the list.
theList.head = head;
// the delete method is invoked on the list.
theList.delete(1);
//print the list to the console.
System.out.println(theList);
}
// not static because we operate on a ListPrac instance.
public int delete(int deleteMe) {
//...
public static class ListNode {
//...
#Override
public String toString(){
String nextNodeAsString = next == null ? "null" : next.toString();
return "{data="+dat+",next="+nextNodeAsString+"}";
}
}
//...
#Override
public String toString(){
return "a list: {head="+head.toString()+"}";
}
}
In the next step you should compare your and the other solution and try to spot the error.
Happy coding :)

write a function to add to the end of linked list [duplicate]

I'm studying for an exam, and this is a problem from an old test:
We have a singly linked list with a list head with the following declaration:
class Node {
Object data;
Node next;
Node(Object d,Node n) {
data = d;
next = n;
}
}
Write a method void addLast(Node header, Object x) that adds x at the end of the list.
I know that if I actually had something like:
LinkedList someList = new LinkedList();
I could just add items to the end by doing:
list.addLast(x);
But how can I do it here?
class Node {
Object data;
Node next;
Node(Object d,Node n) {
data = d ;
next = n ;
}
public static Node addLast(Node header, Object x) {
// save the reference to the header so we can return it.
Node ret = header;
// check base case, header is null.
if (header == null) {
return new Node(x, null);
}
// loop until we find the end of the list
while ((header.next != null)) {
header = header.next;
}
// set the new node to the Object x, next will be null.
header.next = new Node(x, null);
return ret;
}
}
You want to navigate through the entire linked list using a loop and checking the "next" value for each node. The last node will be the one whose next value is null. Simply make this node's next value a new node which you create with the input data.
node temp = first; // starts with the first node.
while (temp.next != null)
{
temp = temp.next;
}
temp.next = new Node(header, x);
That's the basic idea. This is of course, pseudo code, but it should be simple enough to implement.
public static Node insertNodeAtTail(Node head,Object data) {
Node node = new Node(data);
node.next = null;
if (head == null){
return node;
}
else{
Node temp = head;
while(temp.next != null){
temp = temp.next;
}
temp.next = node;
return head;
}
}
If you keep track of the tail node, you don't need to loop through every element in the list.
Just update the tail to point to the new node:
AddValueToListEnd(value) {
var node = new Node(value);
if(!this.head) { //if the list is empty, set head and tail to this first node
this.head = node;
this.tail = node;
} else {
this.tail.next = node; //point old tail to new node
}
this.tail = node; //now set the new node as the new tail
}
In plain English:
Create a new node with the given value
If the list is empty, point head and tail to the new node
If the list is not empty, set the old tail.next to be the new node
In either case, update the tail pointer to be the new node
Here is a partial solution to your linked list class, I have left the rest of the implementation to you, and also left the good suggestion to add a tail node as part of the linked list to you as well.
The node file :
public class Node
{
private Object data;
private Node next;
public Node(Object d)
{
data = d ;
next = null;
}
public Object GetItem()
{
return data;
}
public Node GetNext()
{
return next;
}
public void SetNext(Node toAppend)
{
next = toAppend;
}
}
And here is a Linked List file :
public class LL
{
private Node head;
public LL()
{
head = null;
}
public void AddToEnd(String x)
{
Node current = head;
// as you mentioned, this is the base case
if(current == null) {
head = new Node(x);
head.SetNext(null);
}
// you should understand this part thoroughly :
// this is the code that traverses the list.
// the germane thing to see is that when the
// link to the next node is null, we are at the
// end of the list.
else {
while(current.GetNext() != null)
current = current.GetNext();
// add new node at the end
Node toAppend = new Node(x);
current.SetNext(toAppend);
}
}
}
loop to the last element of the linked list which have next pointer to null then modify the next pointer to point to a new node which has the data=object and next pointer = null
Here's a hint, you have a graph of nodes in the linked list, and you always keep a reference to head which is the first node in the linkedList.
next points to the next node in the linkedlist, so when next is null you are at the end of the list.
The addLast() needs some optimisation as the while loop inside addLast() has O(n) complexity. Below is my implementation of LinkedList. Run the code with ll.addLastx(i) once and run it with ll.addLast(i) again , you can see their is a lot of difference in processing time of addLastx() with addLast().
Node.java
package in.datastructure.java.LinkedList;
/**
* Created by abhishek.panda on 07/07/17.
*/
public final class Node {
int data;
Node next;
Node (int data){
this.data = data;
}
public String toString(){
return this.data+"--"+ this.next;
}
}
LinkedList.java
package in.datastructure.java.LinkedList;
import java.util.ArrayList;
import java.util.Date;
public class LinkedList {
Node head;
Node lastx;
/**
* #description To append node at end looping all nodes from head
* #param data
*/
public void addLast(int data){
if(head == null){
head = new Node(data);
return;
}
Node last = head;
while(last.next != null) {
last = last.next;
}
last.next = new Node(data);
}
/**
* #description This keep track on last node and append to it
* #param data
*/
public void addLastx(int data){
if(head == null){
head = new Node(data);
lastx = head;
return;
}
if(lastx.next == null){
lastx.next = new Node(data);
lastx = lastx.next;
}
}
public String toString(){
ArrayList<Integer> arrayList = new ArrayList<Integer>(10);
Node current = head;
while(current.next != null) {
arrayList.add(current.data);
current = current.next;
}
if(current.next == null) {
arrayList.add(current.data);
}
return arrayList.toString();
}
public static void main(String[] args) {
LinkedList ll = new LinkedList();
/**
* #description Checking the code optimization of append code
*/
Date startTime = new Date();
for (int i = 0 ; i < 100000 ; i++){
ll.addLastx(i);
}
Date endTime = new Date();
System.out.println("To total processing time : " + (endTime.getTime()-startTime.getTime()));
System.out.println(ll.toString());
}
}
The above programs might give you NullPointerException. This is an easier way to add an element to the end of linkedList.
public class LinkedList {
Node head;
public static class Node{
int data;
Node next;
Node(int item){
data = item;
next = null;
}
}
public static void main(String args[]){
LinkedList ll = new LinkedList();
ll.head = new Node(1);
Node second = new Node(2);
Node third = new Node(3);
Node fourth = new Node(4);
ll.head.next = second;
second.next = third;
third.next = fourth;
fourth.next = null;
ll.printList();
System.out.println("Add element 100 to the last");
ll.addLast(100);
ll.printList();
}
public void printList(){
Node t = head;
while(n != null){
System.out.println(t.data);
t = t.next;
}
}
public void addLast(int item){
Node new_item = new Node(item);
if(head == null){
head = new_item;
return;
}
new_item.next = null;
Node last = head;
Node temp = null;
while(last != null){
if(last != null)
temp = last;
last = last.next;
}
temp.next = new_item;
return;
}
}

Pass by value Linked list

I am trying to rearrange a Singly linked list. The initial list will be 1,2,3,4,5
and they have to be sorted in 1,5,2,4,3. I have the code and I am trying to understand how it works. Basically I am stuck at the concept of pass by value in java.
The complete code
public class Test {
public static void main(String[] args) {
LinkedLists linkedList = new LinkedLists();
linkedList.append(1);
linkedList.append(2);
linkedList.append(3);
linkedList.append(4);
linkedList.append(5);
linkedList.reorderList();
}}
class Node {
int data;
Node next;
public Node(int data) {
this.data = data;
}}
class LinkedLists {
Node head;
public void reorderList() {
if (head == null) {
System.out.println(head);
return;
}
Node slowPointer = head;
Node fastPointer = head.next;
System.out.println(slowPointer.hashCode());
System.out.println(head.hashCode());
while (fastPointer != null && fastPointer.next != null) {
fastPointer = fastPointer.next.next;
slowPointer = slowPointer.next;// why head value did not change
}
Node head2 = slowPointer.next;
slowPointer.next = null;// why did the head value change here
LinkedList<Node> queue = new LinkedList<Node>();
while (head2 != null) {
Node temp = head2;
head2 = head2.next;
temp.next = null;
queue.push(temp);
}
while (!queue.isEmpty()) {
Node temp = queue.pop();
temp.next = head.next;
head.next = temp;
head = temp.next;
}
}
public void append(int data) {
if (head == null) {
head = new Node(data);
return;
}
Node current = head;
while (current.next != null) {
current = current.next;
}
current.next = new Node(data);
}}
The value of head does not get changed at line
slowPointer = slowPointer.next;// why head value did not change
But at line
slowPointer.next = null;// why did the head value change here
Why does it change here. Thanks.
Because in the first case you are assigning the object pointed by next to the slowPointer.
But in second case you are modifying the value of 'next' of the object being pointed by the reference slowPointer. So the head object is directly modified.

Adding to end of custom Linked List throws a NPE on "newNode.data = .."

Hi can anyone help me out with a LinkedList issue I am having. I am trying to add a node storing OBJ to the end of my list, but I cannot seem to get why its not working. Below is the code I have so far:
public void addLast(int obj)
{
ListNode newNode = new ListNode();
newNode=head;
while(newNode!=null)
{
newNode=newNode.link;
}
if(newNode==null)
{
newNode.data=obj;
}
I can paste the whole code if needed but this is just the section that I cannot get to work right.
Currently there is about 5 nodes containing data from OBJ so I am traversing the link with a while loop and then I reach the end I insert newNode containing OBJ
The current code throws an null point exception error in this part: newNode.data=obj;.
Why isn't it working? Appreciate any help, Thanks!
if( head == null )
{
//add to head
...
}
else
{
//traverse the list
for( Node tail = head; tail.link != null; tail = tail.link )
;
//add to tail
...
}
First of all if you use your head Node to begin with you don't need to create a node before that. Secondly while you are iterating over your structure you are jumping one step too far.
public void addLast(int obj)
{
if (head == null) {
// If we add an element for the first time
head = new ListNode();
head.data = obj;
} else {
newNode = head;
while (newNode.link != null) {
newNode = newNode.link;
}
// Now newNode.link is null
// Creating the next node
ListNode temp = new ListNode();
temp.data = obj;
// Assigning this new node to the last node's neighbor
newNode.link = temp;
}
}
The condition would be the
while(newNode.link != null)
and initialize before putting into the data
newNode.link = new ListNode();
newNode.data = obj
You are checking if its null and setting its data after that. It will give an NPE. When you reach the end do newNode.link = newNode
ListNode newNode = new ListNode();
newNode.data = obj;
if(head == null)
{
head = newNode;
return
}
ListNode curr = head;
while(curr.link!=null)
{
curr=curr.link;
}
// curr now points to last node
curr.link = newNode
The solution to my answer i now have seems to be working as i want, every time i call an instance of addLast() it stores all current links and adds the OBJ data at the end of the list, the final code is:
public void addLast(int obj)
{
ListNode newNode = new ListNode();
newNode = head;
while (newNode.link != null)
{
newNode = newNode.link;
}
ListNode last = new ListNode();
last.data = obj;
newNode.link = last;
}
Thanks everyone!

Adding items to end of linked list

I'm studying for an exam, and this is a problem from an old test:
We have a singly linked list with a list head with the following declaration:
class Node {
Object data;
Node next;
Node(Object d,Node n) {
data = d;
next = n;
}
}
Write a method void addLast(Node header, Object x) that adds x at the end of the list.
I know that if I actually had something like:
LinkedList someList = new LinkedList();
I could just add items to the end by doing:
list.addLast(x);
But how can I do it here?
class Node {
Object data;
Node next;
Node(Object d,Node n) {
data = d ;
next = n ;
}
public static Node addLast(Node header, Object x) {
// save the reference to the header so we can return it.
Node ret = header;
// check base case, header is null.
if (header == null) {
return new Node(x, null);
}
// loop until we find the end of the list
while ((header.next != null)) {
header = header.next;
}
// set the new node to the Object x, next will be null.
header.next = new Node(x, null);
return ret;
}
}
You want to navigate through the entire linked list using a loop and checking the "next" value for each node. The last node will be the one whose next value is null. Simply make this node's next value a new node which you create with the input data.
node temp = first; // starts with the first node.
while (temp.next != null)
{
temp = temp.next;
}
temp.next = new Node(header, x);
That's the basic idea. This is of course, pseudo code, but it should be simple enough to implement.
public static Node insertNodeAtTail(Node head,Object data) {
Node node = new Node(data);
node.next = null;
if (head == null){
return node;
}
else{
Node temp = head;
while(temp.next != null){
temp = temp.next;
}
temp.next = node;
return head;
}
}
If you keep track of the tail node, you don't need to loop through every element in the list.
Just update the tail to point to the new node:
AddValueToListEnd(value) {
var node = new Node(value);
if(!this.head) { //if the list is empty, set head and tail to this first node
this.head = node;
this.tail = node;
} else {
this.tail.next = node; //point old tail to new node
}
this.tail = node; //now set the new node as the new tail
}
In plain English:
Create a new node with the given value
If the list is empty, point head and tail to the new node
If the list is not empty, set the old tail.next to be the new node
In either case, update the tail pointer to be the new node
Here is a partial solution to your linked list class, I have left the rest of the implementation to you, and also left the good suggestion to add a tail node as part of the linked list to you as well.
The node file :
public class Node
{
private Object data;
private Node next;
public Node(Object d)
{
data = d ;
next = null;
}
public Object GetItem()
{
return data;
}
public Node GetNext()
{
return next;
}
public void SetNext(Node toAppend)
{
next = toAppend;
}
}
And here is a Linked List file :
public class LL
{
private Node head;
public LL()
{
head = null;
}
public void AddToEnd(String x)
{
Node current = head;
// as you mentioned, this is the base case
if(current == null) {
head = new Node(x);
head.SetNext(null);
}
// you should understand this part thoroughly :
// this is the code that traverses the list.
// the germane thing to see is that when the
// link to the next node is null, we are at the
// end of the list.
else {
while(current.GetNext() != null)
current = current.GetNext();
// add new node at the end
Node toAppend = new Node(x);
current.SetNext(toAppend);
}
}
}
loop to the last element of the linked list which have next pointer to null then modify the next pointer to point to a new node which has the data=object and next pointer = null
Here's a hint, you have a graph of nodes in the linked list, and you always keep a reference to head which is the first node in the linkedList.
next points to the next node in the linkedlist, so when next is null you are at the end of the list.
The addLast() needs some optimisation as the while loop inside addLast() has O(n) complexity. Below is my implementation of LinkedList. Run the code with ll.addLastx(i) once and run it with ll.addLast(i) again , you can see their is a lot of difference in processing time of addLastx() with addLast().
Node.java
package in.datastructure.java.LinkedList;
/**
* Created by abhishek.panda on 07/07/17.
*/
public final class Node {
int data;
Node next;
Node (int data){
this.data = data;
}
public String toString(){
return this.data+"--"+ this.next;
}
}
LinkedList.java
package in.datastructure.java.LinkedList;
import java.util.ArrayList;
import java.util.Date;
public class LinkedList {
Node head;
Node lastx;
/**
* #description To append node at end looping all nodes from head
* #param data
*/
public void addLast(int data){
if(head == null){
head = new Node(data);
return;
}
Node last = head;
while(last.next != null) {
last = last.next;
}
last.next = new Node(data);
}
/**
* #description This keep track on last node and append to it
* #param data
*/
public void addLastx(int data){
if(head == null){
head = new Node(data);
lastx = head;
return;
}
if(lastx.next == null){
lastx.next = new Node(data);
lastx = lastx.next;
}
}
public String toString(){
ArrayList<Integer> arrayList = new ArrayList<Integer>(10);
Node current = head;
while(current.next != null) {
arrayList.add(current.data);
current = current.next;
}
if(current.next == null) {
arrayList.add(current.data);
}
return arrayList.toString();
}
public static void main(String[] args) {
LinkedList ll = new LinkedList();
/**
* #description Checking the code optimization of append code
*/
Date startTime = new Date();
for (int i = 0 ; i < 100000 ; i++){
ll.addLastx(i);
}
Date endTime = new Date();
System.out.println("To total processing time : " + (endTime.getTime()-startTime.getTime()));
System.out.println(ll.toString());
}
}
The above programs might give you NullPointerException. This is an easier way to add an element to the end of linkedList.
public class LinkedList {
Node head;
public static class Node{
int data;
Node next;
Node(int item){
data = item;
next = null;
}
}
public static void main(String args[]){
LinkedList ll = new LinkedList();
ll.head = new Node(1);
Node second = new Node(2);
Node third = new Node(3);
Node fourth = new Node(4);
ll.head.next = second;
second.next = third;
third.next = fourth;
fourth.next = null;
ll.printList();
System.out.println("Add element 100 to the last");
ll.addLast(100);
ll.printList();
}
public void printList(){
Node t = head;
while(n != null){
System.out.println(t.data);
t = t.next;
}
}
public void addLast(int item){
Node new_item = new Node(item);
if(head == null){
head = new_item;
return;
}
new_item.next = null;
Node last = head;
Node temp = null;
while(last != null){
if(last != null)
temp = last;
last = last.next;
}
temp.next = new_item;
return;
}
}

Categories