Advertisement
Guest User

Untitled

a guest
Mar 24th, 2019
72
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.18 KB | None | 0 0
  1. import java.io.*;
  2.  
  3. public class LinkedList {
  4.  
  5. Node head;
  6. static class Node {
  7.  
  8. int data;
  9. Node next;
  10.  
  11. Node(int d)
  12. {
  13. data = d;
  14. next = null;
  15. }
  16. }
  17.  
  18. public static LinkedList insert(LinkedList list, int data)
  19. {
  20. // Create a new node with given data
  21. Node new_node = new Node(data);
  22. new_node.next = null;
  23.  
  24. // If the Linked List is empty,
  25. // then make the new node as head
  26. if (list.head == null) {
  27. list.head = new_node;
  28. }
  29. else {
  30. // Else traverse till the last node
  31. // and insert the new_node there
  32. Node last = list.head;
  33. while (last.next != null) {
  34. last = last.next;
  35. }
  36.  
  37. // Insert the new_node at last node
  38. last.next = new_node;
  39. }
  40.  
  41. // Return the list by head
  42. return list;
  43. }
  44.  
  45. public static void printList(LinkedList list)
  46. {
  47. Node currNode = list.head;
  48.  
  49. System.out.print("LinkedList: ");
  50.  
  51. // Traverse through the LinkedList
  52. while (currNode != null) {
  53. // Print the data at current node
  54. System.out.print(currNode.data + " ");
  55.  
  56. // Go to next node
  57. currNode = currNode.next;
  58. }
  59. }
  60.  
  61. // Driver code
  62. public static void main(String[] args)
  63. {
  64. // Empty main, please insert
  65. }
  66. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement