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 { } ;
Example A struct of stock items at a store:.
Separate Definition from Declaration.
Using Typedef Can define your own types using typedef ! General form: typedef ; Examples:.
Doing typedef and definition at once:.
Referencing Struct Members.
Structs and Pointers StockItem x; StockItem *p; p = &x; // p points to x // ways to set quantity to 500:.
Malloc a Struct (StockItem).
Lists
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? X
Flexible List: “Linked List” Insert an item into the middle of the list: Delete an item from the middle of the list: X
Implementing a Linked List of int s.
Allocating a new Node a function to allocate & initialize a node.
Creating a List: Adding to the end.
Creating a List: Adding to the front.
Function to Print a List.
Deleting the First Node of a List info: 5 link: myList info: 3 link: info: 1 link:
Function to Delete first Node.
Delete first Node: return new head.
Function to return true if an item found.
Function to Delete Entire List.
Function to Add Element to End of List.
Deleting the Last Node of a List info: 5 link: myList info: 3 link: info: 1 link:
Function to Delete Last Element.
Inserting into an Ordered List info: 1 link: myList info: 3 link: info: 5 link: 4
Function to Insert into Ordered List.
Using Recursion on Lists
Printing a List using Recursion can think of a list recursively as: a head node plus a list.
Deleting a List using Recursion.
Finding an Item using Recursion.
Compare 2 Lists: true if identical.
Insert into an Ordered List.