CSCI 2720 Lists III - University of Georgia

advertisement
CSCI 2720
Lists III
Eileen Kraemer
University of Georgia
Spring 2007
DLL - Doubly Linked Lists
• Nodes have two pointer fields
 Next
 Prev
Prev
Next
A
B
C
 Next(Prev(P)) and Prev(Next(P)) -- would be nice if
they always evaluated to P, but …
 Next(Prev(P)) -- breaks on first
 Prev(Next(P)) -- breaks on last
DLL
Header
Next
Prev
A
B
C
• Next(Prev(P)) and Prev(Next(P)) now OK
DLLs
•
•
•
•
Forward traversal easy
Backward traversal easy
Insertion before item easy
Insertion after item easy
DLLInsert
Procedure DLLInsert(ptr P,Q):
//Insert node pointed to by P just after node pointed to by Q
Pr ev(P)
 Q


 

Next(P)
Next(Q)

 

Next(Q)
 P


 

Pr ev(Next(Q)) P

DLLDelete
• Procedure DLLDelete(ptr P):
• //Delete cell P from its DLL
 Next(Pr ev( P))   Next( P) 

  

 Pr ev( Next( P))   Pr ev( P) 
DLLs vs. SLLs
• Pro:
 Can delete in O(1) knowing only address of
node to be deleted
 Easy backward traversal
• Con
 Requires 2x the memory for pointers
XOR pointers
• “trick” to compress composite of addresses
in preceding and succeeding nodes into a
single pointer-sized field
• Saves memory
• Requires more elaborate methods to
traverse list (in either direction)
What is XOR?
• Bit-wise exclusive-or
• When applied twice to same value, returns
to original value
• Works like a toggle switch
XOR Example
•
•
•
•
•
Add1 = 4 (0100),
Add2 = 8 (1000)
Result = Add1  Add2 = 1100
Result  Add1 = 1000 (original Add2)
Result  Add2 = 0100 (original Add1)
XOR used in graphics
• To do “rubber-banding”
 Don’t have to remember previous value of pixel
that you overwrite …. Just XOR same value on
that location 2X and it returns to the original
value
Implementing DLL with XOR
• Link(X) =
X (i 1) mod( n  2)  X (i 1) mod( n  2)
• To traverse, need P and Q, pointers to two
adjacent nodes
Traversing with XOR
• Forward(P,Q):
 P  Q

   

 Q   P  Link (Q) 
Traversing with XOR
• Backward(P,Q):
 P   Link ( P)  Q 
   

Q  P

Inserting a new node with XOR
• To insert a new node pointed to by C
between those pointed to by P and Q:
 Link ( P)   Link ( P) Q  C 

 

 Link (Q)   Link (Q) P  C 

 Link (C )   P Q


 

Q
 C


 

Download