If you truly understand the concept of doubly-linked list, these problems would be very easy. Lets start with basic doubly-linked list concept. Doubly-linked list data structure consist of 3 important components: set of data, pointer to address of previous data (*prev), and pointer to address of next data (*next). When you learn linked-list, you will often heard the term "node". Node is simply just a record.
NULL <--- [*prev|data|*next] <---> [*prev|data2|*next] <--> [*prev|data3|*next] --> NULL
Let say that we have
kth nodes and we want to display all of data out into the screen. Assuming
plist is the address of our first node.
while (plist != NULL) {
std::cout << plist->data;
plist = plist->next;
}
To count total nodes, to count nodes that have even or odd data value, or to print backward also use this technique except with some extra conditions.
To add new node in, no matter at what position it will be inserted in (at beginning, at middle, or at the end), you need to allocate memory location to store new node and assign proper *next and *prev address. For example, you want to insert new node at the end of your list. To do so, you need to know the address of your last node. Then, assign the *prev of the new node to the address of the last node and then *next of the new node point to NULL which to determine that it is the end of the list. Then *next of the last node must assign to the address of the new node.
1. Allocating memory for new node (the red text represent new node)
NULL <--- [*prev|data|*next] <---> [*prev|data2|*next] --> NULL [*prev|new_data|*next]
2. Assign *prev of new node and *next of last node (Connecting)
NULL <--- [*prev|data|*next] <---> [*prev|data2|*next] <--> [*prev|new_data|*next]
3. Assign *next of the new node to NULL
NULL <--- [*prev|data|*next] <---> [*prev|data2|*next] <--> [*prev|new_data|*next] --> NULL
Last but not least, removing the node from the list is also important. First you need to know the address of the node you want to delete. Then connect the previous node of node you want to delete to its next node. Then de-allocate its memory
1. (Red-text represent node you want to delete)
NULL <--- [*prev|data|*next] <---> [*prev|data2|*next] <--> [*prev|data3|*next] --> NULL
2. Connect its previous node to its next node
NULL <--- [*prev|data|*next] <-------------------------> [*prev|data3|*next] --> NULL
[*prev|data2|*next]
3. De-allocating its memory
NULL <--- [*prev|data|*next] <---> [*prev|data3|*next] --> NULL
So the most important thing about linked-list is about assigning the right address of next and previous node. More information, go to
http://en.wikipedia.org/wiki/Doubly-linked_list.
These should give half of the answer of your questions and it's matter of how to figure another half of the answer.