Answers for "Add first element to linked list"

0

Add first element to linked list

void push_front(int newElement) {
  
  //1. allocate node
  Node newNode = new Node();
  
  //2. assign data element
  newNode.data = newElement;
  
  //3. assign null to the next and prev
  //   of the new node
  newNode.next = null; 
  newNode.prev = null;

  //4. Check the list is empty or not,
  //   if empty make the new node as head 
  if(head == null) {
    head = newNode;
  } else {
    
    //5. Adjust the links and make the new
    //   node as head
    head.prev = newNode;
    newNode.next = head;
    head = newNode;
  }    
}
Posted by: Guest on January-13-2022

Code answers related to "Add first element to linked list"

Browse Popular Code Answers by Language