Академический Документы
Профессиональный Документы
Культура Документы
Data *Pop()
{ if (isEmpty()) return null;
Data *value = top; top = value->link; return value; }
Data *Remove()
{ Data *value = head;
if (isEmpty()) return NULL;
head = head->link; if (head == NULL) : tail = NULL; return value;
}
int isEmpty() { return (head == null; }
Data peek() { return head; }
Linked List Implementation
See Text Example
• With dynamic memory
– The data structure uses object links.
– Insert/Delete: Search; assignments to change pointers
• With an array (Use indices instead of data links)
– Need to list array, size, and pointer to initial entry.
– Initialization: Create free entry chain.
– Insert: retrieve from free list if any and do normal insertion.
– Delete: Do normal insertion logic and then add to free list.
– The data structure uses primitive links rather than object
links.
Ordered Linked List Insertion
Item first;
void insert(Item *d )
{
Item *previous = null; Item *current = first;
while (current!=NULL && d->key > current->key)
{ previous=current; current=current->next); }
if (previous == NULL) first = d; else previous->next = d;
d->next = current;
}
if (current == NULL)
{ if (previous == NULL) first = current;
else previous->next = d; }
else
{ if (current->previous==NULL)
{ first=d; d->next=current; current->previous=d;}
else { d->previous = current->previous; d->next = current;
current->previous->next = d; current->previous = d;
}
Doubly Linked Removal
int remove(Item *d)
{ Item *current = first;
do
{ if (current == NULL) return NULL;
if (current->key != d->key) {current = current->next; }
} while (!equals(current->key, d->key));
if (current->previous == NULL) first = current->next;
else current->previous->next = current->next;
if (current->next != NULL) current->next->previous = current->previous;
return true;
}
Stack Examples
• Matching pairs of delimiters
• Evaluating infix expressions
– Two stacks
– First convert to postfix and then evaluate
• Expression examples
{…{….[..{.<.{..{…}…}…>..].}..}
500/(1+2*(3+4*5/2))*(3*2+1)