Explain the following lines:

Background information:
Insert at the front of a Deque(this data structure is made of doubly linked list, so a front and back Node pointer).

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
void DequeList::insertionAtFront(int val){
	// Create a new node 
	Node* newNode = new Node();
	newNode->data = val;
	newNode->next = NULL;
	newNode->prev = NULL;
	if(currentSize == 0){
		front = newNode;
		back = front;
	}
	else{
		// Explanation?
		newNode->next = front;
		front->prev = newNode;	
		front = newNode;
	}
	currentSize++;
}



Could you please clarify the process inside else {... } (Lines 13-15)? Also why is it necessary to have front->prev = newNode?
Thanks.
Last edited on
Lets say that you have two items in doubly linked list:
X Y

Each node has pointers 'prev' and 'next'. Where do they point to?

We prepend new node W.
W X Y

What pointers must be updated?


Unrelated to the previous, what is the 'front'?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
struct DequeList {

    struct Node {

        explicit Node( int v ) : val(v) {}
        Node( int v, Node* n, Node* p ) : val(v), next(n), prev(p) {}

        int val ;
        Node* next = nullptr ;
        Node* prev = nullptr ;
    };

    Node* front = nullptr ;
    Node* back = nullptr ;
    std::size_t currentSize = 0 ;

    DequeList() = default ;
    // ...

    // void insertionAtFront(int val) {
    void insertAtFront(int val) {

        if( currentSize == 0 ) { // empty list

            // empty list: this becomes the only node in (both front and back of ) the list
            // the next and prev of this only node are null
            front = back = new Node(val) ;
        }

        else { // the list is not empty

            // the new node added would be the prev of the node currently at the front
            // the next of this new node is the current front of the list
            // and the prev of this new node is null
            front->prev = new Node( val, front, nullptr ) ;

            front = front->prev ; // the front of the list is now the new node that was added
        }

        ++currentSize ; // in either case, the current size goes up by one
    }
};
Topic archived. No new replies allowed.