Merging custom doubly linked list - java

I have two custom made doubly linked list and a method insertAt(int pos,DoublyLinkedList l) that should insert the list l before the given index of the other list. However, after using it, nothing happens, even though when I watch the proccess in debugger everything seems to go fine. Program compiles, it just does not give any result. Here's the minimal example:
public class DoublyLinkedList{
private static final class Node {
protected Object data;
protected Node next, prev;
/* Constructor */
public Node() {
next = null;
prev = null;
data = 0;
}
/* Constructor */
public Node(Object d, Node n, Node p) {
data = d;
next = n;
prev = p;
}
/* Function to set link to next node */
public void setLinkNext(Node n) {
next = n;
}
/* Function to set link to previous node */
public void setLinkPrev(Node p) {
prev = p;
}
/* Funtion to get link to next node */
public Node getLinkNext() {
return next;
}
/* Function to get link to previous node */
public Node getLinkPrev() {
return prev;
}
/* Function to set data to node */
public void setData(Object d) {
data = d;
}
/* Function to get data from node */
public Object getData() {
return data;
}
}
protected Node start;
protected Node end;
public int size;
/* Constructor */
public DoublyLinkedList() {
start = null;
end = null;
size = 0;
}
public void insertBefore(int pos, DoublyLinkedList l) {
Node ptr = start;
if (pos == 1) {
l.end.setLinkNext(start);
start.setLinkPrev(l.end);
} else {
for (int i = 2; i <= size; i++) {
if(i==pos){
ptr.setLinkPrev(l.end);
l.end.setLinkNext(ptr);
Node tmp=ptr;
ptr = ptr.getLinkPrev();
ptr.setLinkNext(l.start);
l.start.setLinkNext(tmp);
size=size()+l.size();
break;
}
ptr=ptr.getLinkNext();
}
}
}
public static void main(String[] args) {
// TODO code application logic here
DoublyLinkedList list1 = new DoublyLinkedList();
list1.insertAtEnd("a");
list1.insertAtEnd("b");
list1.insertAtEnd("c");
list1.insertAtEnd("d");
list1.insertAtEnd("e");
DoublyLinkedList list2 = new DoublyLinkedList();
list2.insertAtEnd("1");
list2.insertAtEnd("2");
list2.insertAtEnd("3");
list2.insertAtEnd("4");
list2.insertAtEnd("5");
list1.display();
list2.display();
list1.insertBefore(3, list2);
list1.display();
list1.size();
}
}
Any help will be appreciated

Look at this part of your code:
ptr.setLinkPrev(l.end);
l.end.setLinkNext(ptr);
Node tmp=ptr;
ptr = ptr.getLinkPrev();
ptr.setLinkNext(l.start);
l.start.setLinkNext(tmp);
it sets the end of the new list as ptr's predecessor, and links it back properly.
a temporary variable keeps the current reference to ptr.
Then you move ptr to refer to its predecessor. But this predecessor is not what used to be ptr's predecessor in the original list. It's the result of step (1) above, the end item of the new list!
Then you tell this item, the end of the new list, to link to the new list's beginning... The new list will now become a circle. But only singly-linked.
Then you link the start's next to what you saved - the old ptr.
As a result your forward links from the old start still go the old way - they have not changed much. But the back links are broken, and the new list's links are broken.
You think nothing changed because your printing method probably just walks the list through its forward links. Try to write another printing method that walks them backwards, it should become interesting...
One way to solve this would be to save ptr's predecessor before you replace it, and use that for forward-linking the new list.

The problem is here:
ptr.setLinkPrev(l.end);
l.end.setLinkNext(ptr);
Node tmp=ptr;
ptr = ptr.getLinkPrev();
//ptr is now the last node of l, not the previous node of original list!!!
//==> you cycle your l list again in the next instruction:
ptr.setLinkNext(l.start);
l.start.setLinkNext(tmp);
size=size()+l.size();
break;
You should save the previous node of ptr BEFORE you start merging...
It should be:
Node tmp = prev.getLinkPrev();
ptr.setLinkPrev(l.end);
l.end.setLinkNext(ptr);
tmp.setLinkNext(l.start);
l.start.setLinkPrev(tmp);
size=size()+l.size();
break;

I figured this out with help of your hint guys, thanks.
public void insertBefore(int pos, DoublyLinkedList l) {
checkOutOfBounds(pos);
Node ptr = start;
if (pos == 1) {
l.end.setLinkNext(start);
start.setLinkPrev(l.end);
start=l.start;
size=size()+l.size();
} else {
for (int i = 2; i <= size; i++) {
if(i==pos){
Node tmp=ptr;
ptr.setLinkPrev(l.end);
l.end.setLinkNext(ptr.getLinkNext());
tmp.setLinkNext(l.start);
l.start.setLinkPrev(tmp);
size=size()+l.size();
break;
}
ptr=ptr.getLinkNext();
}
}
}

Related

Implementation of the 'set' method for a linked List?

I am trying to implement the set method where you pass in the position in a linked list that you want and the value and the set function adds that value into the position specified in the linked list. I have implemented the set function but for some reason The last element disappears in my implementation. I would greatly appreciate any help. Thanks in advance. I would appreciate any expert eyes that will see what I am missing.
/**
* A basic singly linked list implementation.
*/
public class SinglyLinkedList<E> implements Cloneable, Iterable<E>, List<E> {
//---------------- nested Node class ----------------
/**
* Node of a singly linked list, which stores a reference to its
* element and to the subsequent node in the list (or null if this
* is the last node).
*/
private static class Node<E> {
E value;
Node<E> next;
public Node(E e)
{
value = e;
next = null;
}
}
//----------- end of nested Node class -----------
// instance variables of the SinglyLinkedList
private Node<E> head = null; // head node of the list (or null if empty)
private int size = 0; // number of nodes in the list
public SinglyLinkedList() {
} // constructs an initially empty list
// access methods
/**
* Returns the number of elements in the linked list.
*
* #return number of elements in the linked list
*/
public int size() {
return size;
}
/**
* Adds an element to the end of the list.
*
* #param e the new element to add
*/
public void addLast(E e) {
// TODO
}
/**
* Tests whether the linked list is empty.
*
* #return true if the linked list is empty, false otherwise
*/
public boolean isEmpty() {
return size == 0;
}
#Override
public E get(int i) throws IndexOutOfBoundsException {
Node<E> a = head;
if(i<=this.size()) {
int count = 0;
while(count < i) {
count ++;
a = a.next;
}
return a.value;
}
return null;
}
#Override
public E set(int i, E e) throws IndexOutOfBoundsException {
Node<E> current = head;
Node<E> setNode = new Node<E>(e);
if(i==0) {
this.addFirst(e);
}
else if(i==this.size){
this.addLast(e);
}
else {
for(int j=0; current != null && j < (i-1);j++) {
current = current.next;
}
Node<E> temp = current.next;
current.next = setNode;
setNode.next = temp;
}
return setNode.value;
}
// update methods
/**
* Adds an element to the front of the list.
*
* #param e the new element to add
*/
public void addFirst(E e) {
Node<E> first = new Node<>(e);
first.next = this.head;
this.head = first;
this.size++;
}
#SuppressWarnings({"unchecked"})
public boolean equals(Object o) {
// TODO
return false; // if we reach this, everything matched successfully
}
#SuppressWarnings({"unchecked"})
public SinglyLinkedList<E> clone() throws CloneNotSupportedException {
// TODO
return null;
}
/**
* Produces a string representation of the contents of the list.
* This exists for debugging purposes only.
* #return
*/
public String toString() {
for(int i=0;i<this.size();i++) {
System.out.println(this.get(i));
}
return "end of Linked List";
}
public static void main(String[] args) {
SinglyLinkedList <Integer> ll =new SinglyLinkedList <Integer>();
ll.addFirst(5);
ll.addFirst(4);
ll.addFirst(3);
ll.addFirst(2);
ll.set(1,0);
System.out.println(ll);
}
}
Assumptions
addLast method is missing in the code
The error could be there too
Known cause
This code is not incrementing the size inside the set method's for loop.The size is incremented in addLast(possibly) and addFirst and not incremented in other case (final else part)
It is not clear what is planned to do with set method. The way it is implemented now, it behaves more like insert, meaning that it will add new node, bit it does not increase the total count of elements (size).
It the set method is changing the value of the node, which name indicates, then this part is wrong:
else {
for(int j=0; current != null && j < (i-1);j++) {
current = current.next;
}
Node<E> temp = current.next;
current.next = setNode;
setNode.next = temp;
}
It should replace the value instead of adding the new one:
else {
for(int j=0; current != null && j < (i-1);j++) {
current = current.next;
}
current.value=e
}
Also, it looks like the index i is 1-based, while everything else is 0 based. I didn't check the code above, but the concept should be like shown.

Create new head for a list with data

Sorry for a noob question, but the syntax is a bit confusing here. I am asked to fill in the function to insert new element onto the front of a linked list. The code:
class LinkedList
{
public LinkedList ()
{
this.head = null;
}
/* returns true, if the list is empty, else false */
public boolean isEmpty ()
{
return head == null;
}
/* returns the first element of the list, assuming that the list is not empty */
public int front ()
{
return head.data;
}
/* prints the list */
public void print ()
{
System.out.print("(");
for (ListNode i = head; i != null; i = i.next)
System.out.print(i.data + " ");
System.out.println(")");
}
/* inserts x into the beginning of the list */
public void insertFront (int x)
{
/* FILL HERE!!! */
}
}
The code for the nodes:
class ListNode
{
public ListNode()
{
this.data = 0;
this.next = null;
}
public int data;
public ListNode next;
}
I figured I need to create a new node, assign the value of the current head for the next operator, and set the value equal to x. And then finally set the node to be the new head.
Can someone show me how to perform those basic commands.
Just declare your new element as head and let it point to the previous head, which is now the second element.
/* inserts x into the beginning of the list */
public void insertFront(int x)
{
// Temporarily memorize previous head
ListNode previousHead = this.head;
// Create the new head element
ListNode nextHead = new ListNode();
nextHead.data = x;
// Let it point to the previous element which is now the second element
nextHead.next = previousHead;
// Update the head reference to the new head
this.head = nextHead;
}
Here is a small illustration of the process:

Regarding finding the middle element of linked list

I am following the below approach to calculate the middle element from the linked list , but I want is there any built in method or any other approach which can also find the same easily , the approach that I am following is shown bellow..
import test.LinkedList.Node;
public class LinkedListTest {
public static void main(String args[]) {
//creating LinkedList with 5 elements including head
LinkedList linkedList = new LinkedList();
LinkedList.Node head = linkedList.head();
linkedList.add( new LinkedList.Node("1"));
linkedList.add( new LinkedList.Node("2"));
linkedList.add( new LinkedList.Node("3"));
linkedList.add( new LinkedList.Node("4"));
//finding middle element of LinkedList in single pass
LinkedList.Node current = head;
int length = 0;
LinkedList.Node middle = head;
while(current.next() != null){
length++;
if(length%2 ==0){
middle = middle.next();
}
current = current.next();
}
if(length%2 == 1){
middle = middle.next();
}
System.out.println("length of LinkedList: " + length);
System.out.println("middle element of LinkedList : " + middle);
}
}
class LinkedList{
private Node head;
private Node tail;
public LinkedList(){
this.head = new Node("head");
tail = head;
}
public Node head(){
return head;
}
public void add(Node node){
tail.next = node;
tail = node;
}
public static class Node{
private Node next;
private String data;
public Node(String data){
this.data = data;
}
public String data() {
return data;
}
public void setData(String data) {
this.data = data;
}
public Node next() {
return next;
}
public void setNext(Node next) {
this.next = next;
}
public String toString(){
return this.data;
}
}
}
Output:-
length of LinkedList: 4
middle element of LinkedList : 2
The basic algorithm would be
Take two pointers
Make both pointing to first node
Increment first with two nodes and second with one, at a time.
Loop until the 1st loop reaches the end. At this point, the 2nd will be at the middle.
Example:-
while ( p2.next != null ) {
p2 = p2.next;
if (p2.next != null) {
p2 = p2.next;
p1 = p1.next;
}
}
It will definitely work in odd case, for even case you need to check one more condition if first point is allowed to move next but not next to next then both pointers will be at middle you need to decide which to take as middle.
I would recommend using the Java built in
LinkedList<Object e>
It gives you all the functionality you need like getting the length: list.size(), and the middle object:
list.get((list.size())/2);
Options:
Have a double linked-list and go from the back and front at the same time until you get to a common point.
Store the size of the list and simply stop when you've reached this half this size (similar to what the standard API's LinkedList does).
Other than that I don't think you can do better than your algorithm.
public Node getMiddleElement(Node head) {
Node slow_pointer=head;
Node fast_pointer=head;
while(fast_pointer.next!=null && fast_pointer.next.next!=null)
{
slow_pointer=slow_pointer.next;
fast_pointer=fast_pointer.next.next;
}
return slow_pointer;
}
Node mid_elem=PrintMiddleElement(head);
System.out.println(mid_elem.data);
I/P:5 10 15 25 35 25 40 O/P:25
Solution for this question:
Use two indexes, first and second, both initialized to 0
Increment first by 1 and second by 2 * first
Set value of first to middle
Loop will execute until value of second is less than list size
Here is code snippet for getting middle element of list or linked list:
private int getMiddle(LinkedList<String> list) {
int middle = 0;
int size = list.size();
for (int i = 0, j = 0; j < size; j = i * 2) {
middle = i++;
}
return middle;
}
LinkedList<String> list = new LinkedList<>();
list.add("1");
list.add("2");
list.add("3");
list.add("4");
list.add("5");
list.add("6");
list.add("7");
int middle = getMiddle(list);
System.out.println(list.get(middle));

How to add a display method to a Java Linked List implementation that displays only the first and the last 10 items on the list?

UPDATE: Thanks to all who answered I did what I was assigned to do. This is really a great forum and I was surprised to find so many helpful and friendly-minded people here :)
What I did was to modify the print method in the following way:
public static void print(ListNode start){
System.out.println("Printing the first 10 elements on the list:");
System.out.print("{");
ListNode previous = start;
ListNode current = start;
for (int i = 0; i<10; i++){
current=current.next;
}
for(ListNode node = start; node != current; node = node.next){
System.out.print(node);
}
System.out.println("}");
System.out.println("Printing the last 10 elements on the list:");
System.out.print("{");
while(current != null){
previous = previous.next;
current = current.next;
}
for(ListNode node = previous; node != current; node = node.next){
System.out.print(node);
}
System.out.println("}");
System.out.println("End of list");
}
END OF UPDATE
I'm learning Algorithms and Data structures in Java and I need to add a specific display method to an existing exercise Linked List implementation but I don't know how to do it.
So there is a linked list that contains many items (say thousands) and I need a display method that shows only the first and the last 10 items on the list.
Can you suggest to me a way to do it?
The Linked list implementation that I need to work on is the following:
import java.util.*;
public class Main {
public static class ListNode {
//A linked list node. The data field is represented by the field int data
//The next item is referenced by the reverence value next
int data;
ListNode next;
public ListNode(){
this.data = 0; this.next = null;
}
public ListNode(int data){
this();this.data = data;
}
public ListNode(int data, ListNode next){
this.data = data;this.next = next;
}
public String toString() {
return "[" + this.data + "]";
}
//The linked list is referenced by the first node.
//An empty list is referenced by a null reference.
//That's why all methods for the list are public static -
//(null doesn't have methods)
//Returns the beginning of a list with length "length"and
//elements with random values
public static ListNode generate(int length) {
ListNode start = null;
Random rn = new Random();
for(int i = 0; i < length; i++){
start = new ListNode(rn.nextInt(10000), start);
}
return start;
}
//Displays the list to the console from the specified starting point
public static void print(ListNode start){
System.out.print("{");
for(ListNode node = start; node != null; node = node.next){
System.out.print(node);
}
System.out.println("}");
}
//Counts how many elements there are in the list
public static int length(ListNode L){
int k=0;
for(;L!=null;k++,L=L.next);
return k;
}
//Returns a node with key searchd if found in the list
public static ListNode search(ListNode start, int searchd){
for(ListNode node = start; node != null; node = node.next){
if(node.data == searchd){ return node; }
}
return null;
}
//If a node with the specified key is found in the list L
//a new node with the value keyAfter is inserted after it.
public static void insertAfter(ListNode L, int key, int keyAfter){
while(L!=null && L.data!=key)L=L.next;
if(L!=null){
L.next= new ListNode(keyAfter,L.next);
}
}
//Inserts a node with key "keyBefore" before the node
//with the specified key
public static ListNode insertBefore(ListNode L, int key, int keyBefore){
ListNode p = null, r=L;
while(L!=null && L.data!=key){
p=L;L=L.next;
}
if(p!=null){
p.next= new ListNode(keyBefore,p.next);return r;
}
else{
p=new ListNode(keyBefore,L);return p;
}
}
//Inserts a new element with the specified key in a sorted list
//with ascending values so that the list remains sorted
public static ListNode insertOrd(ListNode L, int key){
ListNode p = null, r=L;
while(L!=null && L.data<key){
p=L;L=L.next;
}
if(p!=null){
p.next= new ListNode(key,p.next);return r;
}
else{
p=new ListNode(key,L);return p;
}
}
//Generates a sorted list with a specified lenght
public static ListNode generateOrd(int length) {
ListNode start = null;
Random rn = new Random();
for(int i = 0; i < length; i++){
start = insertOrd(start,rn.nextInt(10000));
}
return start;
}
//Takes two ordered lists and returns a merged and sorted list
//that combines the elements in the original lists
public static ListNode merge(ListNode a, ListNode b){
if(a==null)return b;
if(b==null)return a;
ListNode r = null;
if(a.data<=b.data){
r=a;a=a.next;
}else{
r=b;b=b.next;
}
ListNode last=r;
while(a!=null && b!=null){
if(a.data<=b.data){
last.next=a;a=a.next;
}else{
last.next=b;b=b.next;
}
last=last.next;
}
if(a!=null)last.next=a;else last.next=b;
return r;
}
//Splits a list evenly and returns the beginning of the 2-nd part
public static ListNode split(ListNode L){
int n=length(L)/2;
ListNode t=L;
for(int i=0;i<n-1;i++,t=t.next);
ListNode secPart = t.next;
t.next=null;
return secPart;
}
//Sorts a list in an ascending order
public static ListNode mrgSort(ListNode L){
if(L==null || L.next==null)return L;
ListNode b = split(L);
L=mrgSort(L); b= mrgSort(b);
return merge(L,b);
}
};//End of class ListNode
public static void main(String[] args){
ListNode a = ListNode.generateOrd(10);
ListNode.print(a);
ListNode b = ListNode.generateOrd(10);
ListNode.print(b);
a=ListNode.merge(a,b);
ListNode.print(a);
b=ListNode.split(a);
ListNode.print(a);
ListNode.print(b);
ListNode c = ListNode.generate(20);
ListNode.print(c);
c = ListNode.mrgSort(c);
ListNode.print(c);
}
}
Alright, I am not going to write the code for you but ill tell you how to go about doing it.
Initially say you have two pointers (head1 and head2) which point to the first node of the list. Move head2 ten steps forward keeping head1 at the same place.
Now, after ten steps you have head1 at 0 and head2 at 9th position. Now move both together till head2 hits NULL. Once head2 hits NULL, start moving head1 alone and print each node till head1 reaches head2.
Hope this helps
This is a fairly odd implementation of a Linked list.
What sticks out is
The amount of static members
No class representing the actual list.
The static members in node should be placed in a LinkedList class. Check out the members of the JavaAPIs LinkedList class.
The other members are similar to what is found in the Collections class.
As it stands the easiest solution is as peraueb suggests in the comments follow the print method; i.e. Do as print does, and store the link to the 10:th to last node. noMAD's idea will work fine there.
The usual way to do it would be to have a LinkedList class handle references / links to the first and the last Node. The Node itself should contain links/references to the previous as well as the next node. This is the suggestion of Nactives answer. Now you are manually dealing with those in main(...).
For that you need a reference to your first and your last item.
Best way is also to make it a duuble linked list: http://en.wikipedia.org/wiki/Doubly_linked_list
Basicly, at the front of your list it is still the same.
But now you can also access your list at the end and move to the beginning of your list.

Implementing a Linked List (java)

hello im trying to implement a Linked list in java.
As this is a homework assignment I am not allowed to use the built in LinkedList from java.
Currently I have implemented my Node class
public class WordNode
{
private String word;
private int freq;
private WordNode next;
/**
* Constructor for objects of class WordNode
*/
public WordNode(String word, WordNode next )
{
this.word = word;
this.next = next;
freq = 1;
}
/**
* Constructor for objects of class WordNode
*/
public WordNode(String word)
{
this(word, null);
}
/**
*
*/
public String getWord()
{
return word;
}
/**
*
*/
public int getFreq(String word)
{
return freq;
}
/**
*
*/
public WordNode getNext()
{
return next;
}
/**
*
*/
public void setNext(WordNode n)
{
next = n;
}
/**
*
*/
public void increment()
{
freq++;
}
}
and my "LinkedList"
public class Dictionary
{
private WordNode Link;
private int size;
/**
* Constructor for objects of class Dictionary
*/
public Dictionary(String L)
{
Link = new WordNode(L);
size = 1;
}
/**
* Return true if the list is empty, otherwise false
*
*
* #return
*/
public boolean isEmpty()
{
return Link == null;
}
/**
* Return the length of the list
*
*
* #return
*/
public int getSize()
{
return size;
}
/**
* Add a word to the list if it isn't already present. Otherwise
* increase the frequency of the occurrence of the word.
* #param word The word to add to the dictionary.
*/
public void add(String word)
{
Link.setNext(new WordNode(word, Link.getNext()) );
size++;
}
Im having trouble with implementing my add method correctly, as it has to check the list, for wether the word allready exists and if do not exists, add it to the list and store it alphabetic.
Ive been working on a while loop, but cant seem to get it to work.
Edit: Ive been trying to print the list but it wont print more than the first added word
public void print()
{
WordNode wn = Link;
int size = 0;
while(wn != null && size <= getSize()){
System.out.println(wn.getWord()+","+wn.getFreq(wn.getWord()));
size++;
}
}
Any help is appreciated
Your add method is wrong. You're taking the root node and setting its next value to the new node. So you will never have any more than 2 nodes. And if you ever have 0, it will probably crash due to a null pointer.
What you want to do is set a current value to the root node, then continue getting the next node until that node is null. Then set the node.
WordNode current = Link;
// Check if there's no root node
if (current == null) {
Link = new WordNode(word);
} else {
// Now that the edge case is gone, move to the rest of the list
while (current.getNext() != null) {
/* Additional checking of the current node would go here... */
current = current.getNext();
}
// At the last element, at then new word to the end of this node
current.setNext(new WordNode(word));
}
You need to keep the instance of the previous node so you can set the next value. Since this would cause a problem if there are no nodes to begin with, there needs to be some extra logic to handle a root node differently. If you'll never have 0 nodes, then you can remove that portion.
If you also need to check the values of the variables in order to see if it's there, you can add something to the while loop that looks at the current value and sees if it is equal to the current word you're looking for.
WordNode current = Link;
while (current != null) {
//check stuff on current word
current = current.getNext();
}
Without your loop code, it will be hard to help you with your specific problem. However, just to give you a bit of a hint, based on the instructions you don't actually have to search every node to find the word. This will give you the opportunity to optimize your code a bit because as soon as you hit a word that should come after the current word alphabetically, then you can stop looking and add the word to the list immediately before the current word.
For instance, if the word you're adding is "badger" and your words list are
apple-->avocado-->beehive-->...
You know that beehive should come after badger so you don't have to keep looking. What you will need to implement is a method that can do alphabetical comparison letter-by-letter, but I'll leave that to you ;-)
Assuming that you always insert in alphabetical order it should look something like this:
public void add(String word){
WordNode wn = Link;
WordNode prevNode = null;
while(wn != null){
if(word.equals(wn.getWord())){
//match found, increment frequency and finish
wn.increment();
return;
}else if(word.compareTo(wn.getWord) < 0){
//the word to add should come before the
//word in the current WordNode.
//Create new link for the new word,
//with current WordNode set as the next link
WordNode newNode = new WordNode(word, wn)
//Fix next link of the previous node to point
//to the new node
if(prevNode != null){
prevNode.setNext(newNode);
}else{
Link = newNode;
}
//increase list size and we are finished
size++;
return;
}else{
//try next node
prevNode = wn;
wn = wn.getNext();
}
}
//If we got here it means that the new word
//should be added to the end of the list.
WordNode newNode = new WordNode(word);
if(prevNode == null){
//if list was originally empty
Link = newNode;
}else{
//else append it to the end of existing list
prevNode.setNext(newNode);
}
//increment size and finish
size++;
}
Use this code :
class NodeClass {
static Node head;
static class Node {
int data;
Node next;
//constractor
Node(int d) {
data=d;
next=null;
}
}
static void printList(Node node ) {
System.out.println("Printing list ");
while(node!=null){
System.out.println(node.data);
node=node.next;
}
}
static void push(int data) {
Node node = new Node(data);
node.next = head;
head = node;
}
static void addInLast(int data) {
Node node = new Node(data);
Node n = head;
while(n.next!=null){
n= n.next;
}
n.next = node;
node.next = null;
}
public static void main (String[] args) {
NodeClass linklistShow = new NodeClass();
linklistShow.head = new Node(1);
Node f2 = new Node(2);
Node f3 = new Node(3);
linklistShow.head.next = f2;
f2.next =f3;
printList(linklistShow.head);
push(6);
addInLast(11);
printList(linklistShow.head);
}
}

Categories