Untitled

 avatar
user_2664266
java
2 years ago
2.1 kB
2
Indexable
Never
/*
 * Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license
 * Click nbfs://nbhost/SystemFileSystem/Templates/Classes/Main.java to edit this template
 */
package javaapplication12;

public class JavaApplication12 {

    static node head;

    static class node {

        int data;
        node next;

        node(int d) {
            data = d;
            next = null;
        }
    }

    public static void insert_node(int data) {
        node new_node = new node(data);

        if (head == null) {
            head = new_node;
        } else {

            node temp = head;
            while (temp.next != null) {
                temp = temp.next;
            }

            temp.next = new_node;
        }
    }

    public static void display() {
        if (head == null) {
            System.out.println("no display linked list is empty");
        } else {
            node curr_node = head;
            while (curr_node != null) {
                System.out.print(curr_node.data + "  ");
                curr_node = curr_node.next;
            }
            System.out.println();
        }
    }

    public static void delete_node(int key) {
        node currNode = head;
        node prev = null;
        if (currNode != null && currNode.data == key) {
            head = currNode.next;
            System.out.println("delete key( " + key + " ) done");
            return;
        }
        while (currNode != null && currNode.data != key) {
            prev = currNode;
            currNode = currNode.next;
        }
        if (currNode != null) {
            prev.next = currNode.next;
            System.out.println("delete key( " + key + " ) done");

        } else {
            System.out.println("not found key( " + key + " )to delete");
        }
    }

    public static void main(String[] args) {
        display();
        insert_node(0);
        insert_node(9);
        display();
        delete_node(8);
        delete_node(9);
        display();
    }

}