code.ashish.me

Atom feed

Recently added: 02 Count Of Subset Sum, 416 Partition Equal Subset Sum, 01 Subset Sum, 518 Coin Change 2, 983 Minimum Cost For Tickets

Insertatendofdoublylist

/**
 *
 * Ashish Patel
 * e: ashishsushilPatel@gmail.com
 * w: https://ashish.me
 *
 */

class InsertAtEndOfDoublyList {

  static DoublyNode insertEnd(DoublyNode head, int data) {
    DoublyNode newNode = new DoublyNode(data);
    if(head == null){
      return newNode;
    }
    DoublyNode current = head;
    while(current.next != null){
      current = current.next;
    }
    current.next = newNode;
    newNode.prev = current;
    return head;
  }

  public static void main(String[] args) {
    DoublyNode head = new DoublyNode(10);
    DoublyNode temp1 = new DoublyNode(20);
    DoublyNode temp2 = new DoublyNode(30);
    head.next = temp1;
    temp1.prev = head;
    temp1.next = temp2;
    temp2.prev = temp1;
    head = insertEnd(head, 40);
    printlist(head);
  }

  public static void printlist(DoublyNode head) {
    DoublyNode curr = head;
    while (curr != null) {
      System.out.print(curr.data + " ");
      curr = curr.next;
    }
    System.out.println();
  }
}

Created 2021-12-30T10:56:07+00:00 · Edit