Question:
Write a function to insert an element onto the front of a doubly
linked list of nodes with the following type definition.
struct ListNode {
int data;
ListNode *next; // pointer to next elt in list
ListNode *prev; // pointer to previous elt in list
};
The function should return the head of the new list.
Answer:
ListNode* insertFront(ListNode *old_head, int key) { ListNode *new_head = new ListNode; new_head->data = key; new_head->prev = NULL; new_head->next = old_head; if(old_head) old_head->prev = new_head; return new_head; }(The trickiest thing about this is to remember to check whether old_head is non-NULL before changing its prev pointer.)