Question

Implement the following operation for doubly Linked List: public void insertAt(int position, E data){ } public...

Implement the following operation for doubly Linked List:

public void insertAt(int position, E data){

}

public void insertEnd(E data){

}

public void deleteAt(int position) {

}

public void deleteEnd(){

}

0 0
Add a comment Improve this question Transcribed image text
Answer #1

public void insertAt(int position, E data) {

Node newNode = new Node();

newNode.data = data;

Node ptr = head;

position = position - 1;

for (int i = 1; ; i++) {

if (ptr == null) {

break;

}

if (i == position) {

newNode.next = ptr.next;

ptr.next.prev = newNode;

ptr.next = newNode;

newNode.prev = ptr;

break;

}

ptr = ptr.next;

}

}

public void insertEnd(E data) {

Node new_Node = new Node();

new_Node.data = data;

new_Node.next = head;

new_Node.prev = null;

if (head != null)

head.prev = new_Node;

head = new_Node;

}

private Node deleteNode(Node head, Node del)

{

if (head == null || del == null)

return null;

if (head == del)

head = del.next;

if (del.next != null)

del.next.prev = del.prev;

if (del.prev != null)

del.prev.next = del.next;

del = null;

return head;

}

public void deleteAt(int position)

{

if (head == null || n <= 0)

return;

Node current = head;

int i;

for (i = 1; current != null && i < position; i++)

{

current = current.next;

}

if (current == null)

return;

deleteNode(head, current);

}

NOTE: As per HOMEWORKLIB POLICY I am allowed to answer specific number of questions (including sub-parts) on a single post. Kindly post the remaining questions separately and I will try to answer them. Sorry for the inconvenience caused.

Add a comment
Know the answer?
Add Answer to:
Implement the following operation for doubly Linked List: public void insertAt(int position, E data){ } public...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT