daily pastebin goal
55%
SHARE
TWEET

Untitled

a guest Jun 13th, 2018 51 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. package LinkedList;
  2.  
  3. public class Node {
  4.  
  5. protected Node nextNode;
  6. protected int data;
  7.  
  8. public Node(int data) {
  9.     this.data = data;
  10. }
  11.  
  12. }
  13.  
  14.  
  15. package LinkedList;
  16.  
  17. public class LinkedList {
  18.  
  19. private Node head;
  20.  
  21. public void insertLast(int data) {
  22.  
  23.     Node new_node = new Node(data);
  24.  
  25.     if(head == null) {
  26.         head = new_node;
  27.     }else {
  28.  
  29.         Node n = head;
  30.  
  31.         while(n.nextNode != null) {
  32.             n = n.nextNode;
  33.         }  
  34.  
  35.         n.nextNode = new_node;
  36.     }  
  37. }
  38.  
  39. public void insertFirst(int data) {
  40.  
  41.     Node new_node = new Node(data);
  42.  
  43.     if(head == null) {
  44.  
  45.         head = new_node;
  46.  
  47.     }else {
  48.  
  49.         Node node = head;
  50.         head = new_node;
  51.         head.nextNode = node;
  52.  
  53.     }
  54.  
  55. }
  56.  
  57. public void insertAt(int index,int data) {
  58.  
  59.     int x = 1;
  60.  
  61.     Node node = head;
  62.  
  63.     while(node != null) {
  64.  
  65.         if(index == 0) {
  66.  
  67.             insertFirst(data);
  68.             break;
  69.  
  70.         }else {
  71.  
  72.             node = node.nextNode;
  73.  
  74.             if( index == x ) {
  75.  
  76.                 Node new_node = new Node(data);
  77.                 Node current = node;
  78.                 node = new_node;
  79.                 node.nextNode = current;
  80.                 break;
  81.             }
  82.  
  83.             x++;
  84.  
  85.         }
  86.  
  87.     }
  88.  
  89. }
  90.  
  91. public void print() {
  92.  
  93.     Node node = head;
  94.  
  95.     while(node != null) {
  96.         System.out.println(node.data);
  97.         node = node.nextNode;
  98.     }
  99.  
  100. }
  101.    
  102. package Test;
  103.  
  104. import LinkedList.*;
  105.  
  106. public class Main {
  107.  
  108. public static void main(String[] args) {
  109.  
  110.     LinkedList list = new LinkedList();
  111.     list.insertLast(100);
  112.     list.insertLast(200);
  113.     list.insertLast(300);
  114.     list.insertLast(400);
  115.     list.insertLast(500);
  116.  
  117.     list.insertAt(1, 50);
  118.  
  119.     list.print();
  120.  
  121. }
  122.  
  123. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top