|
| 1 | +import java.io.*; |
| 2 | + |
| 3 | +// Java program to implement |
| 4 | +// a Singly Linked List |
| 5 | +public class LinkedList { |
| 6 | + |
| 7 | + Node head; // head of list |
| 8 | + |
| 9 | + // Linked list Node. |
| 10 | + // This inner class is made static |
| 11 | + // so that main() can access it |
| 12 | + static class Node { |
| 13 | + |
| 14 | + int data; |
| 15 | + Node next; |
| 16 | + |
| 17 | + // Constructor |
| 18 | + Node(int d) |
| 19 | + { |
| 20 | + data = d; |
| 21 | + next = null; |
| 22 | + } |
| 23 | + } |
| 24 | + |
| 25 | + // Method to insert a new node |
| 26 | + public static LinkedList insert(LinkedList list, int data) |
| 27 | + { |
| 28 | + // Create a new node with given data |
| 29 | + Node new_node = new Node(data); |
| 30 | + new_node.next = null; |
| 31 | + |
| 32 | + // If the Linked List is empty, |
| 33 | + // then make the new node as head |
| 34 | + if (list.head == null) { |
| 35 | + list.head = new_node; |
| 36 | + } |
| 37 | + else { |
| 38 | + // Else traverse till the last node |
| 39 | + // and insert the new_node there |
| 40 | + Node last = list.head; |
| 41 | + while (last.next != null) { |
| 42 | + last = last.next; |
| 43 | + } |
| 44 | + |
| 45 | + // Insert the new_node at last node |
| 46 | + last.next = new_node; |
| 47 | + } |
| 48 | + |
| 49 | + // Return the list by head |
| 50 | + return list; |
| 51 | + } |
| 52 | + |
| 53 | + // Method to print the LinkedList. |
| 54 | + public static void printList(LinkedList list) |
| 55 | + { |
| 56 | + Node currNode = list.head; |
| 57 | + |
| 58 | + System.out.print("LinkedList: "); |
| 59 | + |
| 60 | + // Traverse through the LinkedList |
| 61 | + while (currNode != null) { |
| 62 | + // Print the data at current node |
| 63 | + System.out.print(currNode.data + " "); |
| 64 | + |
| 65 | + // Go to next node |
| 66 | + currNode = currNode.next; |
| 67 | + } |
| 68 | + } |
| 69 | + |
| 70 | + // Driver code |
| 71 | + public static void main(String[] args) |
| 72 | + { |
| 73 | + /* Start with the empty list. */ |
| 74 | + LinkedList list = new LinkedList(); |
| 75 | + |
| 76 | + // |
| 77 | + // ******INSERTION****** |
| 78 | + // |
| 79 | + |
| 80 | + // Insert the values |
| 81 | + list = insert(list, 1); |
| 82 | + list = insert(list, 2); |
| 83 | + list = insert(list, 3); |
| 84 | + list = insert(list, 4); |
| 85 | + list = insert(list, 5); |
| 86 | + list = insert(list, 6); |
| 87 | + list = insert(list, 7); |
| 88 | + list = insert(list, 8); |
| 89 | + |
| 90 | + // Print the LinkedList |
| 91 | + printList(list); |
| 92 | + } |
| 93 | +} |
0 commit comments