How position based sequence ADT inserts an element in O(1) time? - java

I was reading about position based sequences. (Michael T.Goodrich) chapter-4 (Sequences).
What I understood is that the positional sequence keeps on adding nodes in linear order. (Based on the Doubly linked list ) moreover, each node may point to some other node/s.
For example, take a simple tree having four nodes a,b,c,d implemented by positional sequence.P (having nodes p1,p2,p3,p4)
Now if I want to add new tree node "e" as the right child of "b."For this I will add this node in p5, then I will make references of e.
Book says it adds a node in O(1) time.
My point is, To add e as right child of b, don't we need the position of b which we will get from the position of "a"(link hopping). How come it is not O(n).
one of the solution I found in Stackoverflow itself is the following code...
public interface Position{
Object element();
}
Make a class Node which implements Position interface:
public class Node implements Position {
private Object data;
private Node next;
private Node prev;
public Node(Node prev, Object data, Node next){
this.prev = prev;
this.data = data;
this.next = next;
}
public Object element() // Method of interface Position
{
return data;
}
public void setData(Object data)
{
this.data = data;
}
public void setNext(Node next)
{
this.next = next;
}
public void setPrev(Node prev)
{
this.prev = prev;
}
public Node getNext()
{
return next;
}
public Node getPrev()
{
return prev;
}
}
Make a class List implementing the List ADT:
// this is a List ADT implemented using a Doubly Linked List
public class List{
private Node first;
private Node last;
private int size;
List()
{
first = null;
last = null;
size = 0;
}
public int getSize()
{
return size;
}
public boolean isEmpty()
{
return (size==0);
}
// Accessor methods
public Position first()
{
return first;
}
public Position last()
{
return last;
}
public Position before(Position p) throws Exception
{
Node n = (Node) p;
try{
return n.getPrev();
}catch(NullPointerException ex)
{
throw new Exception("Position Doesn't Exists");
}
}
public Position after(Position p) throws Exception
{
Node n = (Node) p;
try{
return n.getNext();
}catch(NullPointerException ex)
{
throw new Exception("Position Doesn't Exists");
}
}
// Update methods
public void insertFirst(Object data)
{
Node node;
if(isEmpty())
{
Node prev = null;
Node next = null;
node = new Node(prev,data,next);
first = node;
last = node;
}
else
{
Node prev = null;
Node next = first;
node = new Node(prev,data,next);
first.setPrev(node);
first = node;
}
size++;
}
public void insertLast(Object data)
{
Node node;
if(isEmpty())
{
Node prev = null;
Node next = null;
node = new Node(prev,data,next);
first = node;
last = node;
}
else
{
Node prev = last;
Node next = null;
node = new Node(prev,data,next);
last.setNext(node);
last = node;
}
size++;
}
public void insertBefore(Position p, Object data) throws Exception
{
Node cur = (Node) p;
Node prev;
try{
prev = cur.getPrev();
}catch(NullPointerException ex)
{
throw new Exception("Position Doesn't Exists");
}
Node next = cur;
Node node;
node = new Node(prev,data,next);
next.setPrev(node);
if(cur!=first)
prev.setNext(node);
else
first=node;
size++;
}
public void insertAfter(Position p, Object data) throws Exception
{
Node cur = (Node) p;
Node prev = cur;
Node next;
try{
next = cur.getNext();
}catch(NullPointerException ex)
{
throw new Exception("Position Doesn't Exists");
}
Node node;
node = new Node(prev,data,next);
prev.setNext(node);
if(cur!=last)
next.setPrev(node);
else
last=node;
size++;
}
public Object remove(Position p) throws Exception
{
Node n = (Node) p;
Object data = n.element();
if(isEmpty())
{
throw new Exception("List is Empty");
}
else
{
Node prev,next;
if(n==first && n==last)
{
first = null;
last = null;
}
else if(n==first)
{
prev = null;
next = n.getNext();
next.setPrev(prev);
first = next;
}
else if(n==last)
{
prev = n.getPrev();
next = null;
prev.setNext(next);
last = prev;
}
else
{
prev = n.getPrev();
next = n.getNext();
prev.setNext(next);
next.setPrev(prev);
}
size--;
}
return data;
}
}
PEACE

I understand this situation as following. For add new item into the list we have to perform to tasks:
First one: find target item, after which we want to add new item.
Second one: add item and change links.
As you correctly noted, in case of linked list, first operation depends on the amount of item in the list, and will take (maximally) O(n). But, for example in case of array list it can take O(1).
I guess, book says about second task, when target item is already found. And this operation really will take constant amount of operations - O(1), if you are working with linked list. The same operation on array list can take O(n).
Regarding to your comment. Just compare:
Position based
get(i) is O(n)
add(item) is O(1) advantage
addToPosition(i, item) is O(n)
delete(item) is O(1) advantage
delete(i) is from O(1) to O(n)
Ranked based
get(i) is O(1) advantage
add(item) is from O(1) to O(n)
addToPosition(i, item) from O(1) to O(n)
delete(item) is from O(1) to O(2n)
delete(i) is from O(1) to O(n)
So, you should to know advantages of both of types, for use it depending on situation. For example, if you need large amount of add and delete operations - you should use LinkedList, but when you need just access items by index and there is few of add and delete operations - choose ArrayList.

Related

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;
}
}

How can I remove the last node of a Linked List in java?

I need to implement two methods removeFirst and removeLast of a LinkedList in Java
The first method i solved it like this:
#Override
public E removeFirst() {
if(isEmpty()){
throw new NoSuchElementException();
}
E element = top.next.data;
top.next = top.next.next;
numElements--;
return element;
}
I'm having problems with removeLast method
public E removeLast() {
if(isEmpty()){
throw new NoSuchElementException();
}
for (int i = 0; i < numElements;i++) {
}
}
My idea is using a for cycle to look for the last element, but i don't know what to do after that
Any suggestions?
My Node class is the following:
public class Node<E> {
E data;
Node<E> next;
public Node(E data) {
this(data,null);
}
public Node(E data, Node<E> next) {
this.data = data;
this.next = null;
}
#Override
public String toString () {
return data.toString();
}
}
We have to keep two pointers previous and current. Since we are keeping a record for the number of elements in the list we can use for loop to traversal the list and find the last node pointed by currentNode pointer and previous node pointed by previousNode pointer. At last, update the previous next pointer to null and return currentNode data.
public E removeLast() {
if(isEmpty()){
throw new NoSuchElementException();
}
Node previousNode = top;
Node currentNode = top;
for (int i = 0; i < numElements -1 ;i++) {
previousNode = currentNode;
currentNode = currentNode.next;
}
// removed the last element and return the data
previousNode.next = null;
numElements--
return currentNode.data;
}
removeFirst and removeLast already exist in the LinkedList class (LinkedList javadoc). No need to create them from scratch then.
Something like this may work, it's hard to say without seeing your list class because I can't test it:
public E removeLast() {
if(isEmpty()){
throw new NoSuchElementException();
}
Node<E> node = top;
while (true) {
Node<E> nextNode = node.next;
if (nextNode.next == null) {
node.next = null;
return nextNode.data;
} else {
node = nextNode;
}
}
}
But it's worth adding that usually in a singly linked list, you want the containing class to keep a tail pointer (otherwise you can't append to the end efficiently). If you do this, you will need to update your tail as well.
And another comment, if you do find yourself removing the last on a regular basis, you want to switch to a doubly linked list...and why aren't you just using the builtin java.util.LinkedList class? Is this for a school project or something?
This logic shall work -
Node <E> tmp;
tmp = next;
while(tmp.next.next != null)
tmp = tmp.next;
tmp.setNext(null);
So if we have 1->3->4->null
Whenever it gets to 3 it shall setNext to null
so the new array will look like this 1->3->null
public node removelast() {
if(isEmpty())
return null;
node temp =head;
node temp2 =head.getNext();
while(temp!=null && temp2!=null) {
if(temp2.getNext()==null) {
tail=temp;
temp.setNext(null);
}
temp2=temp2.getNext();
temp=temp.getNext();
}
if(head.getNext()==null)
tail=head;
return tail;
}

Insert items into Custom LinkedList in Order

I'm trying to insert items into a custom linked list, while keeping the list in order.
My work up to now is this:
public class CustomList {
public CustomList() {
this.first = null;
}
public void insert(Comparable newThing) {
Node point = this.first;
Node follow = null;
while (point != null && point.data.compareTo(newThing) < 0) {
follow = point;
point = point.next;
}
if (point == null) {
Node newNode = new Node(newThing);
newNode.next = this.first;
this.first = newNode;
} else {
Node newNode = new Node(newThing);
newNode.next = point;
if (follow == null) {
this.first = newNode;
} else {
follow.next = newNode;
}
}
}
private Node first;
private class Node {
public Comparable data;
public Node next;
public Node(Comparable item) {
this.data = item;
this.next = null;
}
}
}
The output I get from this looks like it orders parts of the list, then starts over.
Example (I'm sorting strings):
Instead of getting something like a,b,c,...,z
I get a,b,c,...,z,a,b,c,...,z,a,b,c,...,z
So it looks like it doesn't "see" the whole list at certain points.
This is part of a HW assignment, so I'd appreciate suggestions, but let me try to figure it out myself!
What happens if you insert an element which is greater than all your existing elements?
You want to insert the element at the end, but in fact you are inserting it at start. And any later elements will then inserted before this (if they are smaller), or again at start.

java combine two linkedlist

I have a question for combining two linkedlist. Basically, I want to append one linkedlist to the other linkedlist.
Here is my solution. Is there a more efficient way to do it without looping the first linkedlist? Any suggestion would be appreciated.
static Node connect(LinkedList list1, LinkedList list2) {
Node original = list1.first;
Node previous = null;
Node current = list1.first;
while (current != null) {
previous = current;
current = current.next;
}
previous.next = list2.first;
return original;
}
Use list1.addAll(list2) to append list2 at the end of list1.
For linked lists, linkedList.addAll(otherlist) seems to be a very poor choice.
the java api version of linkedList.addAll begins:
public boolean addAll(int index, Collection<? extends E> c) {
checkPositionIndex(index);
Object[] a = c.toArray();
so even when you have 2 linked lists, the second one gets converted to an array, then re-constituted into individual elements. This is worse than just merging 2 arrays.
I guess this is your own linked list implementation? With only a pointer to next element, the only way to append at the end is to walk all the elements of the first list.
However, you could store a pointer to the last element to make this operation run in constant time (just remember to update the last element of the new list to be the last element of the added list).
The best way is to append the second list to the first list.
1. Create a Node Class.
2. Create New LinkedList Class.
public class LinkedList<T> {
public Node<T> head = null;
public LinkedList() {}
public void addNode(T data){
if(head == null) {
head = new Node<T>(data);
} else {
Node<T> curr = head;
while(curr.getNext() != null) {
curr = curr.getNext();
}
curr.setNext(new Node<T>(data));
}
}
public void appendList(LinkedList<T> linkedList) {
if(linkedList.head == null) {
return;
} else {
Node<T> curr = linkedList.head;
while(curr != null) {
addNode((T) curr.getData());
curr = curr.getNext();
}
}
}
}
3. In the Main function or whereever you want this append to happen, do it like this.
LinkedList<Integer> n = new LinkedListNode().new LinkedList<Integer>();
n.addNode(23);
n.addNode(41);
LinkedList<Integer> n1 = new LinkedListNode().new LinkedList<Integer>();
n1.addNode(50);
n1.addNode(34);
n.appendList(n1);
I like doing this way so that there isn't any need for you to pass both these and loop again in the first LinkedList.
Hope that helps
My Total Code:
NOTE: WITHOUT USING JAVA API
class Node {
Node next;
int data;
Node(int d){
data = d;
next = null;
}
}
public class OddEvenList {
Node head;
public void push(int new_data){
Node new_node = new Node(new_data);
new_node.next = head;
head = new_node;
}
Node reverse(Node head){
Node prev = null;
Node next = null;
Node curr = head;
while(curr != null){
next = curr.next;
curr.next = prev;
prev = curr;
curr = next;
}
head = prev;
return head;
}
Node merge(Node head1, Node head2){
Node curr_odd = head1;
Node curr_even = head2;
Node prev = null;
while(curr_odd != null){
prev = curr_odd;
curr_odd = curr_odd.next;
}
prev.next = curr_even;
return head1;
}
public void print(Node head){
Node tnode = head;
while(tnode != null){
System.out.print(tnode.data + " -> ");
tnode = tnode.next;
}
System.out.println("Null");
}
public static void main(String[] args) {
// TODO Auto-generated method stub
OddEvenList odd = new OddEvenList();
OddEvenList even = new OddEvenList();
OddEvenList merge = new OddEvenList();
odd.push(1);
odd.push(3);
odd.push(5);
odd.push(7);
odd.push(9);
System.out.println("Odd List: ");
odd.print(odd.head);
System.out.println("Even List: ");
even.push(0);
even.push(2);
even.push(4);
even.push(6);
even.push(8);
even.print(even.head);
System.out.println("After Revrse: --------------------");
Node node_odd =odd.reverse(odd.head);
Node node_even = even.reverse(even.head);
System.out.println("Odd List: ");
odd.print(node_odd);
System.out.println("Even List: ");
even.print(node_even);
System.out.println("Meged: --------------");
Node merged = merge.merge(node_odd, node_even);
merge.print(merged);
}
}

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