13
Common Complex C Structures C-minar 6 July 2004

Common Complex C Structures

Embed Size (px)

DESCRIPTION

Common Complex C Structures. C-minar 6 July 2004. To cover today:. Linked list Doubly linked list Binary Tree N-ary Tree. Linked List. What if you need to store ordered information where finding the ‘next’ element is necessary where insertion should be painless - PowerPoint PPT Presentation

Citation preview

Page 1: Common Complex C Structures

Common ComplexC Structures

C-minar

6 July 2004

Page 2: Common Complex C Structures

To cover today:

• Linked list

• Doubly linked list

• Binary Tree

• N-ary Tree

Page 3: Common Complex C Structures

Linked List

• What if you need to store – ordered information– where finding the ‘next’ element is necessary– where insertion should be painless

• Then, the linked list is for you

Page 4: Common Complex C Structures

Linked List

• How to do Linked Lists:– Always keep a pointer to the head– Always point ‘tail’ element’s NEXT

to NULL

HEAD*

ListElem

NEXT*

ListElem

NEXT*

ListElem

NEXT*. . .

NULL

Page 5: Common Complex C Structures

Linked List: Adding

• Adding to a linked list:

1. Create new n:ListElem

2. n:ListElem.NEXT = h:NEXT

3. h:NEXT =n:ListElem

b:ListElem

b:NEXT*hNEXT*

n:ListElem

n:NEXT*

Page 6: Common Complex C Structures

Linked List: Subtracting

• Subtracting

1. h:NEXT = n:ListElem.NEXT

2. free n:ListElem

b:ListElem

b:NEXT*h:NEXT*

n:ListElem

n:NEXT*

Page 7: Common Complex C Structures

Linked List

• What to watch out for:– Dangling pointers (from adding/subtracting in

the wrong order)– Not pointing to NULL at the end– Accidentally losing your HEAD*

Page 8: Common Complex C Structures

Doubly-Linked List

• What if you need to store– A list that is traversable in more than one way

(i.e., backward and forward)– To be able to arbitrarily reorder the list– To be able to have a linked list, yet see

behind you.

Page 9: Common Complex C Structures

Doubly-Linked ListHEAD*

ListElem

NEXT*

ListElem

NEXT*

ListElem

NEXT*. . .

NULL

PREV* PREV* PREV*

Page 10: Common Complex C Structures

Binary Tree

• What if you need to– rapidly get to values in a table– sort these values to be easily accessed– drastically reduce time required to access

data– be able to leap tall buildings in a single bound

• Binary tree is what you nee(d)!

Page 11: Common Complex C Structures

Binary Tree

node

RIGHT*LEFT*

ROOT*

node

RIGHT*LEFT*

node

RIGHT*LEFT*

Page 12: Common Complex C Structures

N-ary Tree

ROOT*

node

_a* _b* _c* _n*...

node

_a* _b* _c* _n*...

node

_a* _b* _c* _n*...

node

_a* _b* _c* _n*...

Page 13: Common Complex C Structures

Homework

• See website