Está en la página 1de 50

Data Structures

³an arrangement of data in a computer¶s memory´


m er iew mf Data Structure
Data structure Advantages Disadvantages

Array Quick Insertion, very fast Slow search, slow


access if index known. deletion, fixed size.
Ordered array Quicker search than Slow insertion and
unsorted array deletion, fixed size
Stack Provides last-in first out Slow access to
access. other items
Queue Provides first-in, first-out Slow access to
access other items
Linked list Quick insertion, quick Slow search
deletion.
Binary tree Quick search, insertion. Deletion algorithm
is complex.
or most data structures, you need to
know how to ,

r `nsert a new data item.


r Search for a specified item.
r Delete a specified item.
r How to iterate through all the items
in a data structure.
Stacks
Stack ?
r A data structure which allows insertions
and deletions through one end (top) is
called a stack.
r A stack is a last in, first out (L` m) data
structure
r `tems are remo ed from a stack in the re erse
order from the way they were inserted
Stack Operations
r Push
!lacing a data item on the top of the stack is called
›  it.

r Pop
¦emo ing it from the top of the stack is called
››› it.

r Peek
!ush and !op are the two primary stack operations.
Howe er, it¶s sometimes useful to be able to read the
alue from the top of the stack without remo ing it.
The peek operation does this.
Pushing and popping
ë
    
M    

 or  

r `f the bottom of the stack is at location ë, then an


empty stack is represented by  or
 ë
r To add (push) an element, either:
r Increment M  and store the element in
MM , or
r Store the element in M M and increment
 M
After popping

ë  


 
     
 or  

rTo remo e (pop) an element, either:


rGet the element from MM  and decrement
M , or
rDecrement  M and get the element in
M M
Defining a Stack
# define S`  
typedef struct { 
int item [S`
int top
 Stack 


oid main( ) 
{

Stack s
s.top = - 

... 
... 

top -
void push( Stack *s, int value )
int is ull( Stack s ) {
s->item [++ s ->top] = value
{ 
return s.top = = SIZE - 
 int pop( Stack *s)
{
return s ->item [s ->top --]

int ismpty( Stack s)
{ int peek (Stack s)
{
return s.top = = - return s.item[s.top]
 
Some uses of stacks
r Stacks are used for:

ü Any sort of nesting (such as parentheses)


ü  aluating arithmetic expressions (and
other sorts of expression)
ü `mplementing function or method calls
ü Keeping track of pre ious choices (as in
backtracking)
ü Keeping track of choices yet to be made
Performing calculations
r To e aluate an expression, such as   , you
need M  stacks: one for operands (numbers), the
other for operators: going left to right,
r `f you see a number, push it on the number stack
r `f you see an operator,
r o  the top of the operator stack holds an operator
of equal or higher precedence:
r pop the old operator

r pop the top two alues from the number stack and
apply the old operator to them
r push the result on the number stack

r push the new operator on the operator stack

r At the end, perform any remaining operations


Example:   
: push  on number stack
: push on op stack
 : push  on number stack
 : because  has higher precedence than , push 
onto op stack
 : push  onto number stack
: because has lower precedence than :
pop , , and 
compute , and push  onto number stack
push onto op stack
 : push  onto number stack
end : pop ,  and , compute  , push 
pop , , and , compute  , push 
(at the top of the stack) is the answer
Oueue
Oueue
rOueues are used to model real-world situations
such as people waiting in a bank, airplanes
waiting to take off, or data packets waiting to be
transmitted o er the `nternet.

rThere are arious in your computer¶s


operating system. There¶s a printer queue where
print jobs wait for the printer to be a ailable.

rUsing a queue guarantees the processes stay in


order until they can be processed.
Array implementation of queues
r A queue is a first in, first out ( ` m) data
structure
r This is accomplished by inserting at one end (the
rear) and deleting from the other (the front)
ë  
 
p   

 M  ë  

r Ôo insert: put new element in location , and set


 to
r Ôo delete: take element from location ë, and set
 M to

Array implementation of queues


 M  ë  

`nitial queue:  

After insertion:  

After deletion: 

 M 
 
r Notice how the array contents ³crawl´ to the right
as elements are inserted and deleted
r This will be a problem after a while!
Defining a Oueue
# define S` 
typedef struct {
char list[S`[
int front, rear
 Oueue
oid main( )
{
Oueue q
q.front = 
q.rear = 
...
...

int isfull ( Queue q)
{
return q.rear = = SIZE ± 


int isempty(Queue q)
{
return q.rear = = q.front

void insert (Queue *q, char *str)
{
q->rear = q->rear + 
strcpy(q->list[q->rear], str)

char * delete ( Queue *q)
{
char str[]
q->front = q->front + 
strcpy(str, q->list[q->front])
return str

void display (Queue q)
{
int i
for(i= q.front+ i<= q.rear i++)
puts(q.list[i])

ircular Oueue

r The draw back of the abo e Oueue


implementation can be remo ed by making
the Oueue a circular one in the sense that as
soon as a pointer exceeds the S`, it
should be reset to .
ircular arrays
r We can treat the array holding the queue elements
as circular (joined at the ends)

ë  


 




    


r lements were added to this queue in the order , ,
,

, , and will be remo ed in the same order


r Use:    ! " #$
and:  ! " #$
ull and empty queues
r `f the queue were to become completely full, it would
look like this:
ë  
 


   


 

r `f we were then to remo e all eight elements, making the


queue completely empty, it would look like this:
ë  
 



 
This is a problem!
ull and empty queues: solutions
r Solution #: Keep an additional ariable
ë  
 


   

  


 

Solution #: (Slightly more efficient) Keep a gap between


r
elements: consider the queue full when it has 
elements ë  
 


  

  


int isfull ( Queue q)
{
return (q.rear+) % SIZE = = q.front


int isempty(Queue q)
{
return q.rear = = q.front

oid insert (Oueue *q, char *str)
{
q->rear = (q->rear + ) % S`
strcpy(q->list[q->rear, str)


char * delete ( Oueue *q)


{
char str[
q->front = (q->front + )%S`
strcpy(str, q->list[q->front)
return str

oid display (Oueue q)
{
int i = q.front
while( i != q.rear){
i= (i+) % S`
puts(q.list[i)


Linked Lists

³a sequence of nodes´
!reliminaries
r mptions for implementing an ADT List
r Array has a fixed size
r Data must be shifted during insertions and
deletions
r Linked list is able to grow in size as
needed
r Does not require the shifting of items during
insertions and deletions
Anatomy of a linked list

r A linked list consists of:


r A sequence of nodes
'(

 %  &

ach node contains a alue


and a link (pointer or reference) to some other node
The last node contains a null link
The list is accessed ia a header (which contains a
reference to the first node in the list)
´ore terminology
r A node¶s successor is the next node in the
sequence
r The last node has no successor
r A node¶s predecessor is the pre ious node in
the sequence
r The first node has no predecessor
r A list¶s length is the number of elements in it
r A list may be empty (contain no elements)
Singly-linked lists
r Here is a singly-linked list (SLL):
'(

 %  &

r ach node contains a alue and a link to its


successor (the last node has no successor)
r The header points to the first node in the list (or
contains the null link if the list is empty)
Node
typedef struct Node
{
int item
struct Node *next
Link

data item
next
Linked List

head

data item data item


NULL data
NULLitem data item
NULL
NULL
next next next next

A LL
Tra ersing a SLL (animation)



%


void displaylist(Link *head)
{
Link *current = head
while(current!=NULL)
{
printf("%d",current->item)
current = current->next


`nserting after (animation)
&

%

ind the node you want to insert after


F copy the link from the node that's already in the list

  change the link in the node that's already in the list


Link* findnode(Link *head,int key)
{
Link *current = head
while(current->item != key)
{
if(current->next == NULL)
return NULL
else
current = current->next

return current

void insertfirst(Link **head, int val)
{
Link *newnode = (Link *) malloc(sizeof(Link))
newnode->item = val
newnode->next = *head
*head = newnode
printf("inserted %d",newnode->item)


Link* deletefirst(Link **head)


{
Link *temp = *head
*head = (*head) ->next
return temp

Deleting an element from a SLL
‡ To delete the first element, change the link in the header
%

‡ To delete some other element, change the link in its predecessor


%

‡ Deleted nodes will e entually be garbage collected


Link* deletenode(Link **head,int key)
{
Link *current = *head
Link *pre ious
while(current->item != key)
{
if(current->next == NULL)
return NULL
else
{
pre ious = current
current = current->next


if(current == *head)
*head=current->next
else
pre ious->next = current ->next
return current

oid main()
{
int choice, al
Link *head
head=NULL
clrscr()
do
{
printf(".`nsert irst\n. Delete irst\n. ind\n
Delete\n.Display\n. exit\nhoice:")
scanf("%d",&choice)
switch(choice)
{
case :
printf("Value?") scanf("%d",& al)
insertfirst(&head, al)
break
case :
{
Link *delnode = deletefirst(&head)
if(!delnode)
printf("List empty")
else
printf("deleted alue %d",delnode->item)
break

case :
{
int key
Link *keynode
printf("nter key:")scanf("%d",&key)
keynode = findnode(head,key)
if(!keynode)
printf("Not found")
else
printf(" ound the node with item %d",keynode->item)
break

case :
{
int key
Link *keynode
printf("nter key to delete:")scanf("%d",&key)
keynode = deletenode(&head,key)
if(!keynode)
printf("Not found")
else
printf(³Deleted the node with item %d",keynode->item)
break

case :
displaylist(head)

while(choice!=)


Doubly-linked lists
r Here is a doubly-linked list (DLL):
)''

 % 

r ach node contains a alue, a link to its successor


(if any), and a link to its predecessor (if any)
r The header points to the first node in the list 6 
to the last node in the list (or contains null links if
the list is empty)
Ôo delete the node to which current points

r (current->pre )->next = current->next


r (current->next)->pre = current->pre 
Ôo insert a new node point to by newnode
before the node pointed to by current.
r newnode->next = cur
r newnode->pre = cur ->pre 
r current->pre = newnode
r newnode->pre ->next= newnode
Deleting a node from a DLL
r Node deletion from a DLL in ol es changing M  links

)''

 % 

r Deletion of the first node or the last node is a


special case
DLLs compared to SLLs
r Ad antages: r Disad antages:
r an be tra ersed in r ¦equires more space
either direction (may r List manipulations
be essential for some are slower (because
programs) more links must be
changed)
r Some operations,
r Greater chance of
such as deletion and ha ing bugs
inserting before a (because more links
node, become easier must be
manipulated)

También podría gustarte