Lets see simple Java code to create custom singly LinkedList and maintaining the same order. Also lets traverse the LinkedList and make sure the LinkedList created properly or not. Here we have class called NODE to store the node details like data and next link. MyLinkedList class used to create LinkedList and to print all the values in LinkedList by traversing all nodes from start to end.
OUTPUT:
class NODE { int data; NODE next = null; public NODE(int data) { this.data = data; } } public class MyLinkedList { public static void main(String[] args) { int array[] = new int[] { 11, 12, 13, 14, 15, 16, 17, 18 }; MyLinkedList obj = new MyLinkedList(); //Create linkedlist based all array values NODE start = obj.createLinkedList(array); //print all the values in linkedlist obj.traverseLinkedList(start); } /* * Create LinkedList and return the start pointer/node */ public NODE createLinkedList(int[] array) { NODE start = null; for (int i : array) { NODE tmp = new NODE(i); if (start == null) { start = tmp; } else { NODE mover = start; while (mover.next != null) { mover = mover.next; } mover.next = tmp; } } return start; } /* * Print/traverse the linkedlist all values */ public void traverseLinkedList(NODE start) { while (start != null) { System.out.println(start.data); start = start.next; } } }
OUTPUT:
11 12 13 14 15 16 17 18
No comments:
Write comments