Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package com.its101.prwk05_06;
- public class DoublyLinkedList {
- // node of the doubly linked list
- public static class Node {
- String data;
- Node previous;
- Node next;
- public Node(String data) {
- this.data = data;
- }
- }
- // declare head node and last node
- Node head, last = null;
- // createNode() creates new node to the list
- public void createNode(String data) {
- // create new node
- Node newNode = new Node(data);
- // if list is empty
- if(head == null) {
- // both head and last will point to newNode
- head = last = newNode;
- // head node's previous will point to null
- head.previous = null;
- // last node's next will point to null, as it is the last node of the list
- last.next = null;
- } else {
- // newNode will be added after last node such that last node's next will point to newNode
- last.next = newNode;
- // newNode's previous will point to last node
- newNode.previous = last;
- // newNode will become new last node
- last = newNode;
- // it is last node, last node next will point to null
- last.next = null;
- }
- }
- // printNode() prints the nodes of the list
- public void printNode() {
- // node current will point to head
- Node current = head;
- if (head == null) {
- System.out.println("List is empty");
- return;
- }
- System.out.println("Nodes of doubly linked list: ");
- while (current != null) {
- // prints each node by incrementing the pointer.
- System.out.print(current.data + " ");
- current = current.next;
- }
- System.out.println();
- }
- public static void main(String[] args) {
- DoublyLinkedList studentsList = new DoublyLinkedList();
- //Create new nodes to the Linked List and assign a data value
- studentsList.createNode("ralph");
- studentsList.createNode("espe");
- studentsList.createNode("glen");
- studentsList.createNode("nomer");
- studentsList.createNode("angelo");
- //Prints the nodes-value present in the list
- studentsList.printNode();
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement