Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public class Algoritmi {
- public static void main(String[] args) {
- LinkedList list = new LinkedList();
- list.insert_node_at_end(1);
- list.insert_node_at_end(2);
- list.insert_node_at_end(3);
- list.print();
- list.delete_node(2);
- list.print();
- }
- }
- class LinkedList {
- class Node {
- int data;
- Node next;
- public Node(int x) {
- data = x;
- next = null;
- }
- }
- Node head; // starting node of linked list
- public void insert_node_at_beginning(int x) {
- if(head == null) {
- head = new Node(x);
- return;
- }
- Node new_node = new Node(x);
- new_node.next = head;
- head = new_node;
- }
- public void insert_node_at_end(int x) {
- if(head == null) {
- head = new Node(x);
- return;
- }
- Node new_node = new Node(x);
- Node tmp = head;
- while(tmp.next != null) {
- tmp = tmp.next;
- }
- tmp.next = new_node;
- }
- public void delete_node(int x) {
- Node current_node = head;
- Node prev_node = null;
- while(current_node != null && current_node.data != x) {
- prev_node = current_node;
- current_node = current_node.next;
- }
- prev_node.next = current_node.next;
- }
- public void print() {
- Node tmp = head;
- while(tmp != null) {
- System.out.print(tmp.data + " --> ");
- tmp = tmp.next;
- }
- System.out.println();
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement