Advertisement
javatechie

Linked List

Aug 26th, 2020
1,708
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.51 KB | None | 0 0
  1. package com.javatechie;
  2.  
  3. public class Node<T> {
  4.  
  5.     T data;
  6.     Node next;
  7.  
  8.     public Node(T data) {
  9.         this.data = data;
  10.         this.next = null;
  11.     }
  12. }
  13.  
  14.  
  15. package com.javatechie;
  16. public class LinkedList {
  17.  
  18.     Node head;
  19.  
  20.  
  21.     public LinkedList add(LinkedList list, int data) {
  22.  
  23.         /** Create a new node with given data
  24.          **/
  25.         Node newNode = new Node(data);
  26.         newNode.next = null;
  27.  
  28.         /** If the Linked List is empty, then make the new node as head
  29.          **/
  30.  
  31.         if (list.head == null) {
  32.             list.head = newNode;
  33.         } else {
  34.  
  35.             /**if list is not empty then head must point to last node
  36.              * then traverse till end
  37.              **/
  38.  
  39.             Node last = list.head;
  40.             while (last.next != null) {
  41.                 // Go to next node
  42.                 last = last.next;
  43.             }
  44.  
  45.             /** Insert the new_node at last node  **/
  46.             last.next = newNode;
  47.         }
  48.  
  49.         return list;
  50.     }
  51.  
  52.  
  53.     public static void traverse(LinkedList list) {
  54.         Node currentNode = list.head;
  55.         while (currentNode != null) {
  56.             System.out.println(currentNode.data);
  57.             // Go to next node
  58.             currentNode = currentNode.next;
  59.         }
  60.  
  61.     }
  62.  
  63.     public static void main(String[] args) {
  64.         LinkedList list = new LinkedList();
  65.         list.add(list, 15);
  66.         list.add(list, 8);
  67.         list.add(list, 48);
  68.  
  69.         traverse(list);
  70.     }
  71. }
  72.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement