Advertisement
StefiIOE

1.0

Sep 22nd, 2020
1,296
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.49 KB | None | 0 0
  1.  
  2. //a linked list node
  3. public class Node {
  4.     int data;
  5.     Node next;
  6.     Node(int data, Node next){
  7.         this.data=data;
  8.         this.next=next;
  9.     }
  10. }
  11. class Main {
  12.     // helper function to return new linked list node from heap
  13.     public static Node newNode(int key) {
  14.         Node node = new Node(key, null);
  15.         return node;
  16.     }
  17.  
  18.     // helper function to print linked list
  19.     public static void printList(Node head) {
  20.         Node ptr = head;
  21.         while (ptr != null) {
  22.             System.out.print(ptr.data + " -> ");
  23.             ptr = ptr.next;
  24.  
  25.         }
  26.         System.out.println("null");
  27.     }
  28. // function to add a new node at the tail end of the list instead of its head
  29.     public static Node appendNode(Node head , int key){
  30.         Node current = head;
  31.         Node node = newNode(key);
  32.         //special case for length 0
  33.         if(current == null){
  34.          head = node;
  35.         }
  36.         else {
  37.             while (current.next!=null){
  38.                 current=current.next;
  39.  
  40.             }
  41.             current.next=node;
  42.         }
  43.         return head;
  44.  
  45.     }
  46.     //main method to implement linked list
  47.     public static void main (String [] args){
  48.         //input keys
  49.         int [] keys = {1 , 2 , 3 , 4 };
  50.         // points to the head node of the linked list
  51.         Node head = null;
  52.         for(int key : keys){
  53.             head = appendNode(head , key);
  54.         }
  55.         //print linked list
  56.         printList(head);
  57.     }
  58. }
  59.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement