Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public class Program {
- public static void main(String[] args) {
- DoublyLinkedList list = new DoublyLinkedList();
- list.insert_at_end(30);
- list.insert_at_end(20);
- list.insert_at_end(10);
- list.insert_between(30, 20, 50);
- list.print();
- list.delete_node(50);
- list.print();
- }
- }
- class DoublyLinkedList {
- class Node {
- int info;
- Node next; // sledbenik
- Node prev; // prethodnik
- public Node( int x) {
- info = x;
- next = null;
- prev = null;
- }
- }
- Node head = null;
- void insert_at_beggining(int x) {
- if(head == null) {
- head = new Node(x);
- return;
- }
- Node new_node = new Node(x);
- new_node.next = head;
- head.prev = new_node;
- head = new_node;
- }
- void insert_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;
- new_node.prev = tmp;
- }
- void insert_between(int x, int y, int new_value) {
- Node x_node = head;
- while(x_node.info != x) {
- x_node = x_node.next;
- }
- Node y_node = x_node.next;
- Node new_node = new Node(new_value);
- x_node.next = new_node;
- new_node.prev = x_node;
- new_node.next = y_node;
- y_node.prev = new_node;
- }
- void delete_node(int x) {
- Node tmp = head;
- while(tmp.info != x) {
- tmp = tmp.next;
- }
- tmp.prev.next = tmp.next;
- tmp.next.prev = tmp.prev;
- }
- void print() {
- Node tmp = head;
- while(tmp != null) {
- System.out.print(tmp.info + " --> ");
- if(tmp.next == null) {
- break;
- }
- tmp = tmp.next;
- }
- System.out.println();
- while(tmp != null) {
- System.out.print(tmp.info + " <-- ");
- if(tmp.prev == null) {
- break;
- }
- tmp = tmp.prev;
- }
- System.out.println();
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement