350 likes | 510 Views
APS105. Lists. Structures. Structures. Arrays allow a collection of elements All of the same type How to collect elements of different types? Structures; in C: struct General form: struct { <variable declarations> } <identifier list>;. Example.
E N D
APS105 Lists
Structures • Arrays allow a collection of elements • All of the same type • How to collect elements of different types? • Structures; in C: struct • General form: struct { <variable declarations> } <identifier list>;
Example • A struct of stock items at a store: .
Using Typedef • Can define your own types using typedef! • General form: typedef <type> <yourTypeName>; • Examples: .
Structs and Pointers StockItem x; StockItem *p; p = &x; // p points to x // ways to set quantity to 500: .
Intro • A list is a sequence of items • can implement lists different ways: • a group of variables • an array • using pointers (as we will see) • Typical list operations • start a new, empty list • insert a new element into the list • find an item with a certain value in the list • delete an item from the list • print the list • Abstract Data Type (ADT) • A list is an example of an ADT • An ADT is a concept • there are multiple ways to implement an ADT
The Problem with Arrays • Insert an item into the middle of the list: • Delete an item from the middle of the list: • What if the array isn’t big enough? 9 X 9
Flexible List: “Linked List” • Insert an item into the middle of the list: • Delete an item from the middle of the list: 5 3 1 6 2 6 7 5 3 1 6 2 6 7 9 5 3 1 6 2 6 7 X
Allocating a new Node • a function to allocate & initialize a node .
Deleting the First Node of a List myList info: 5 link: info: 3 link: info: 1 link:
Deleting the Last Node of a List myList info: 5 link: info: 3 link: info: 1 link:
Inserting into an Ordered List myList info: 1 link: info: 3 link: info: 5 link: 4
Printing a List using Recursion • can think of a list recursively as: a head node plus a list .