Documenti di Didattica
Documenti di Professioni
Documenti di Cultura
Linked lists
Node organization
Basic element of a linked list is a "record" structure of at least two fields (a class
definition with these instance variables). The object that holds the data and refers to
the next element in the list is called a node.
next ptr is a reference to the next element in the structure. There can be multiple
reference fields but we won't consider that now. pointer/reference/link are
synonymous in this discussion.
Example
insertion of the value 8 into the above list (middle of the list)
Insertion
of the value 2 (at the head/beginning of the list)
Insertion
of the value 19 (at the tail of the list)
Deletion
of the value 7
1. Define the instance variables to hold data and refer to the next node in the list.
2. Define a null node constructor (default).
3. Define a non-empty node constructor; this requires a link to the next node
passed as a parameter
Creating elements
An empty node:
A node containing data but doesn't point to anything; a single node list.
Recommendation: DRAW PICTURES! Draw the nodes and links from for the
above three statements.
Null pointer exceptions
You may have already seen this error. It arises when you have a reference variable
that really isn't referencing anything (as in aNode above).
For example the code aNode.next would throw the null pointer exception. There is
no object to which you can refer a next
temp = new NodeType;
temp->data = 450;
temp->next = NULL;
head->next = temp;
Deleting a node
void LLdelete(NodePtr& head, int
value)
{
NodePtr prev;
NodePtr cur = head;
void LLdelete(NodePtr& head, int
value)
while(cur && cur->data != value){
{
prev = cur;
if(head == NULL) return;
cur = cur->next;
}
if(head->data == value){
if(cur == NULL) return; //not
NodePtr cur = head;
found
head = head->next;
delete cur;
if(cur == head){ //delete first
} else {
value
LLdelete(head->next,value);
head = cur->next;
}
} else { //delete middle or end
}
value
prev->next = cur->next;
}
delete cur;
}
Head Nodes
Managing the insertion and deletion of the first element is a special case, especially in
non-recursive solutions.
This special case handling can be eliminated by creating a special "head node"
In your case (assuming that node is defined such that next contains address of next node
and data contains data in the current node) temp is the current node, temp->next refers to
the next node of the linked list, temp->next->data refers to the data in the next node of the
linked list. This may change if the node is defined
I'm reading up on linked lists here and I'm kind of confused. I've drawn it out but it still looks
like they are the same thing.
Traversing through a linked list: