LINKED LISTS AND POINTERS
- When someone cuts into the middle of a queue (array based), it leads to a domino-like effect forcing everyone behind the person to move: Insert Op
- When someone decides to leave the queue people behind have to move. Delete Op
- Data movement operations O(n)
- Linked list data structures improve processing efficiency.
- Tradeoff: space efficiency.
Linked Lists
- A collection of elements called nodes.
- Each node contains a data portion and a pointer.
- Data portion in all nodes are of the same type.
- Pointer in a node contains the location of the node.
- Entire list is referenced by a separate head pointer.
- Head pointer points to the first node in the list.
- Special value (NULL) is assigned to a pointer pointing to an empty linked list.
- Last node in the list contains a NULL pointer.
Head Previous Current Next Pointers
- To facilitate movement through the linked list two special pointers called previous and current are used.
- When list is empty previous and current are NULL.
- When list contains at least one node, head always points to the first node.
- Following an insertion operation, current points to the most recently inserted node.
- Following a removal operation, current points to the node after the most recently deleted node.
- Following a next operation, current points to the next node after the previous current one.
Initializing Pointer Variables
- A NULL pointer is represented in C++ as a value 0. By convention we use the symbolic constant NULL.
constant NULL=0
- Pointer variable can be initialized as
ptr =NULL;
- Pointer variable can be assigned the value of another pointer variable of the same type.
- Pointer variable can be initialized to point to its type.
ptr = new int;
fig 1:
NEW
Defining pointer types
Initializing Headers
Example:
struct node;
typedef node *node_ptr;
struct node{int data;
node_prt next;
}
node_ptr p,q;
- p=get_node(1);
- q=get_node(2);
p->next=q;
p->data=5;
p->next->data=66;
p->->=get_node(7);
Example: Creating Lists
DELETE
- new initializes a pointer variable. Holds a dynamic memory value.
- delete returns a memory to the system stack.
delete ptr;
Traverse a list
Insert in a list