Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package com.javatechie;
- public class Node<T> {
- T data;
- Node next;
- public Node(T data) {
- this.data = data;
- this.next = null;
- }
- }
- package com.javatechie;
- public class LinkedList {
- Node head;
- public LinkedList add(LinkedList list, int data) {
- /** Create a new node with given data
- **/
- Node newNode = new Node(data);
- newNode.next = null;
- /** If the Linked List is empty, then make the new node as head
- **/
- if (list.head == null) {
- list.head = newNode;
- } else {
- /**if list is not empty then head must point to last node
- * then traverse till end
- **/
- Node last = list.head;
- while (last.next != null) {
- // Go to next node
- last = last.next;
- }
- /** Insert the new_node at last node **/
- last.next = newNode;
- }
- return list;
- }
- public static void traverse(LinkedList list) {
- Node currentNode = list.head;
- while (currentNode != null) {
- System.out.println(currentNode.data);
- // Go to next node
- currentNode = currentNode.next;
- }
- }
- public static void main(String[] args) {
- LinkedList list = new LinkedList();
- list.add(list, 15);
- list.add(list, 8);
- list.add(list, 48);
- traverse(list);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement