Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package LinkedList;
- public class Node {
- protected Node nextNode;
- protected int data;
- public Node(int data) {
- this.data = data;
- }
- }
- package LinkedList;
- public class LinkedList {
- private Node head;
- public void insertLast(int data) {
- Node new_node = new Node(data);
- if(head == null) {
- head = new_node;
- }else {
- Node n = head;
- while(n.nextNode != null) {
- n = n.nextNode;
- }
- n.nextNode = new_node;
- }
- }
- public void insertFirst(int data) {
- Node new_node = new Node(data);
- if(head == null) {
- head = new_node;
- }else {
- Node node = head;
- head = new_node;
- head.nextNode = node;
- }
- }
- public void insertAt(int index,int data) {
- int x = 1;
- Node node = head;
- while(node != null) {
- if(index == 0) {
- insertFirst(data);
- break;
- }else {
- node = node.nextNode;
- if( index == x ) {
- Node new_node = new Node(data);
- Node current = node;
- node = new_node;
- node.nextNode = current;
- break;
- }
- x++;
- }
- }
- }
- public void print() {
- Node node = head;
- while(node != null) {
- System.out.println(node.data);
- node = node.nextNode;
- }
- }
- package Test;
- import LinkedList.*;
- public class Main {
- public static void main(String[] args) {
- LinkedList list = new LinkedList();
- list.insertLast(100);
- list.insertLast(200);
- list.insertLast(300);
- list.insertLast(400);
- list.insertLast(500);
- list.insertAt(1, 50);
- list.print();
- }
- }
Add Comment
Please, Sign In to add comment