IQOD #12
a) What is a Linked List? and explain the difference between a singly-linked list and a double-linked (or doubly-linked) lists
A Linked list a data structure that is a collection of objects(data-records) in which each object has a a pointer to the next item in the list.
Imagine: A->B->C->D->NULL
a singly-linked list has 1 link , namely to the next item in the list. a Doubly linked listed has 2 pointers: One to the Next Item, but also one to the previous Item which makes traversing the list much easier
Imagine if you will: NULL<-A<->B<->C<->D->NULL
b) Implement a basic doubly-linked list and write a function to reverse it:
First the basic implementation would be something like this:
Code:
struct MPGHNode
{
int iData; //Whatever Data we store in this thing, lets do int
MPGHNode* pPrev; //Previous Node
MPGHNode* pNext; //Next Node
}
We have a pointer to the next and previous nodes in the list and our 'data' for this node , in this case an int.
Now this is a very convenient data structure because if you wanted to step through all the nodes from beginning to end you could simply do this:
Code:
MPGHNode* current = A;
while(current!=NULL)
{
//do something with current->iData;
//Now move to the next node
current = current->pNext;
}
To understand how to reverse it let's imagine we have some data.
I'll write it out step by step (& very inefficiently

) so you can follow what is going on to make this list:
Code:
MPGHNode* A = new MPGHNode();
MPGHNode* B = new MPGHNode();
MPGHNode* C = new MPGHNode();
MPGHNode* D = new MPGHNode();
A->pPrev = NULL;
A->pNext = B;
A->iData = 1;
B->pPrev = A;
B->pNext = C;
B->iData = 2;
C->pPrev = B;
C->pNext = D;
C->iData = 3;
D->pPrev = C;
D->pNext = NULL;
D->iData = 4;
//Now set a pointer to the beginning of our list and call our reverse
MPGHNode* pList = A;
Reverse(&pList);
Ok so now we have to reverse it.. when you think about it for a while the easiest method becomes:
THe Last Node(called the tail) becomes the First Node (called the head), and all the Prev/Next Pointers are swapped..
Code:
void Reverse(MPGHNode** head)
{
// Empty list or 1 item in the list
if(!*head || !(*head)->pNext)
{
return;
}
// Set first element in the temporary list
MPGHNode* temp_Head = *head;
MPGHNode* currentNode = NULL;
*head = (*head)->pNext;
temp_Head->pNext = NULL;
while(*head)
{
currentNode = *head;
*head = (*head)->pNext;
// Insert node at the front of
// the temporary list
currentNode->pNext = temp_Head;
currentNode->pPrev = NULL;
temp_Head->pPrev = currentNode;
temp_Head = currentNode;
}
// Update head with the temporary
// list
*head = temp_Head;
}
Before we call Reverse you'll notice that in order the value of each iData member is 1,2,3,4.
Now when we returned it's 4,3,2,1. We passed in the Address of our 'pList' Pointer to the reverse
method because we need to change where it points to.
Post some feedback if this makes sense to you guys or if you're having a hard time understanding and i'll try to explain more