lecture 1 introduction linked lists function pointers

Upload: uploadingperson

Post on 02-Jun-2018

216 views

Category:

Documents


0 download

TRANSCRIPT

  • 8/10/2019 Lecture 1 Introduction Linked Lists Function Pointers

    1/28

    Computing 2 2015x1 Summer Session

    Linked Lists and FunctionPointersLecturer

    Angela Finlayson

  • 8/10/2019 Lecture 1 Introduction Linked Lists Function Pointers

    2/28

    COMPILING

    For compiling for normal use

    gccWallWerrorOo prog prog.c

    For compiling to run gdb

    gccWallWerrorgdwarf-2o prog prog.c

    For compiling to run valgrind gccWallWerrorgo prog prog.c

    Compiling with more than 1 c file, normal use

    gccWallWerrorOo prog prog.c f2.c f3.c f4.c

  • 8/10/2019 Lecture 1 Introduction Linked Lists Function Pointers

    3/28

    WHAT IS A LINKED LIST?

    Linked lists:

    sequential collection of items (i.e. no random access)

    we can only get to the second by accessing the first, and so on

    we cant access the nth element of a list directly

    easy to re-arrange

    deleting or inserting is simple

    self-referent structure (may be cyclic)

    a list element contains a link to another list element

  • 8/10/2019 Lecture 1 Introduction Linked Lists Function Pointers

    4/28

    WHAT IS A LINKED LIST?

    A linked list is a set of items where each item is part of a

    node that also contains a link to a node. (We also call the lis

    items list elements)

    The final element:

    1.contains a null link, pointing to no node, or

    2.refers to a dummy node (also called sentinel) containing no ite

    3. may be the first node (hence the list is circular)

  • 8/10/2019 Lecture 1 Introduction Linked Lists Function Pointers

    5/28

    typedef int Item;

    typedef struct node * link;

    struct node {

    Item item;

    link next;

    };

    Sedgewick

    WHAT IS A LINKED LIST?

    A possible C implementation: (Please see tutorial 1

    for another implementation) insert definition forItem here

    item next

    5item next

    3

    http://localhost/Users/keller/Teaching/11s1/lectures/01/Week01.keyhttp://localhost/Users/keller/Teaching/11s1/lectures/01/Week01.keyhttp://localhost/Users/keller/Teaching/11s1/lectures/01/Week01.keyhttp://localhost/Users/keller/Teaching/11s1/lectures/01/Week01.keyhttp://localhost/Users/keller/Teaching/11s1/lectures/01/Week01.keyhttp://localhost/Users/keller/Teaching/11s1/lectures/01/Week01.keyhttp://localhost/Users/keller/Teaching/11s1/lectures/01/Week01.keyhttp://localhost/Users/keller/Teaching/11s1/lectures/01/Week01.keyhttp://localhost/Users/keller/Teaching/11s1/lectures/01/Week01.keyhttp://localhost/Users/keller/Teaching/11s1/lectures/01/Week01.key
  • 8/10/2019 Lecture 1 Introduction Linked Lists Function Pointers

    6/28

    for (curr = start; curr != NULL; curr = curr->next) {

    >

    }

    raversing a list

    link x = malloc (sizeof *x); // RIGHT

    link y = malloc(sizeof(struct node)); //RIGHT

    link z = malloc(sizeof(link)); //WRONG

    Memory allocation

    COMMON OPERATIONS ON LISTS

  • 8/10/2019 Lecture 1 Introduction Linked Lists Function Pointers

    7/28

  • 8/10/2019 Lecture 1 Introduction Linked Lists Function Pointers

    8/28

    OPERATIONS ON LISTS

    Remove the first item in the list

    //Remove the first node from the list and free mem.

    void deleteFirstItem (link ls);

    this interface doesnt work!

    or pass a pointer to the linkeither return new list as result:

  • 8/10/2019 Lecture 1 Introduction Linked Lists Function Pointers

    9/28

    SOME OPERATIONS ON LISTS

    Delete the first item from a list:

    item next

    5item next

    3item next

    2item next

    4

    list

    list = deleteFirstItem(list);

    item next

    5item next

    3item next

    4

    list

  • 8/10/2019 Lecture 1 Introduction Linked Lists Function Pointers

    10/28

    OPERATIONS ON LISTS

    Delete function

    Delete after element curr:

    //delete node after curr from list and free memory

    void deleteNext (link curr);

    item next

    5item next

    3

    curr

    item next

    5

    curr

  • 8/10/2019 Lecture 1 Introduction Linked Lists Function Pointers

    11/28

    PROBLEM: DELETION

    Deletion is awkward, as we always have to keep track of theprevious node:

    Can we delete a node if we only have the pointer to the

    node itself?

    We may need to traverse the whole list (if we have a reference to

    the head) to find the predecessor of curr! Idea: every node stores a link to the previous node, in addition to

    the link to the next node

    prev->next = curr->next;free (curr);

  • 8/10/2019 Lecture 1 Introduction Linked Lists Function Pointers

    12/28

    link reverse (link list) {

    }

    A SINGLY LINKED LIST EXAMPLE

    Implement a function which given a linked list, reverses theorder of items

  • 8/10/2019 Lecture 1 Introduction Linked Lists Function Pointers

    13/28

    link reverse (link list) {

    SINGLY LINKED LIST EXAMPLE

    Implement a function which given a linked list, reverses theorder of items

    link tmp;

    link curr = list;

    link rev = NULL;

    while (curr != NULL) {

    tmp = curr->next;

    curr->next = rev;

    rev = curr;

    curr = tmp;}

    return rev;

    }

  • 8/10/2019 Lecture 1 Introduction Linked Lists Function Pointers

    14/28

    /Assume our items can be compared using

    // , = etc.

    // If there are duplicate smallest items

    just move the

    // first occurrence.

    link smallestFirst (link list) {

    }

    ANOTHER SINGLY LINKED LIST EXAMPLE Implement a function which given a linked list, finds the node

    with the smallest item in the list and moves it to the front of thelist. Other nodes remain unchanged.

    homework!!!!

  • 8/10/2019 Lecture 1 Introduction Linked Lists Function Pointers

    15/28

    DOUBLY LINKED LISTS

    Move forward and backward in such a list

    Delete node in a constant number of steps

    prevprev previtem item itemnext next next

    typedef struct dnode * dlink;

    typedef struct dnode {

    Item item;dlink next;

    dlink prev;

    } ;

  • 8/10/2019 Lecture 1 Introduction Linked Lists Function Pointers

    16/28

    DOUBLY LINKED LISTS

    Deleting nodes

    easier, more efficient Other basic list operations

    pointer to previous node is necessary in many

    operations, doesnt have to be maintained separately for

    doubly linked lists

    twice the number of pointer manipulations necessary for

    most list operations memory overhead to store additional pointer

  • 8/10/2019 Lecture 1 Introduction Linked Lists Function Pointers

    17/28

    #include

    #include

    #include "lists.h"

    voiddeleteNext(link curr){

    if(curr !=NULL){

    link delNode =curr->next;

    if(delNode !=NULL){

    curr->next =delNode->next;

    free(delNode);

    }

    }

    }

    link deleteFirstItem(link list){

    if(list !=NULL){

    link delNode =list;

    list =list->next;

    free(delNode);

    }

    returnlist;

    }

    voidprintList(link list){

    link curr;

    for(curr =list;curr !=NULL;curr=curr->next){

    printf("%d ",curr->item);

    }

    printf("\n");

    }

    link newList(){

    returnNULL;

    }

    link newNode(Item item){

    link n =(link)malloc(sizeof(*n));

    n->item =item;

    n->next =NULL;

    returnn;

    }

    //O(n)

    link insertEnd(link list,link n){

    link curr;

    if(list ==NULL){

    list =n;}else{

    for(curr =list;curr->next !=NULL;curr =curr->next){

    }

    curr->next =n;

    }

    returnlist;

    }

    //O(1)

    link insertFront(link list,link n){

    n->next =list;

    returnn;}

  • 8/10/2019 Lecture 1 Introduction Linked Lists Function Pointers

    18/28

    Traversing the list (insert at front or end)

    it is cheaperto insert a node at the front than the end,

    because you dont

    have to traverse the entire list ifyou insert a node at the front of the list (see

    insertEnd, insertFront)

    oif you have to traverse nothing (insertFront), we

    say it is of an order 1 since the number of

    elements in the list does not affect the number of

    things you have to check (i.e. O(1))

    o

    if you traverse a million things since there are a

    million members, it is of order n (i.e. O(n))

  • 8/10/2019 Lecture 1 Introduction Linked Lists Function Pointers

    19/28

    FUNCTION POINTERS

    C can pass functions by passing a pointer to them.

    E.g. a pointer to a function mapping int int

    int (*fun)(int)

    Function pointers ...

    are references to memory addresses of functions

    are pointer values and can be assigned/passed

    Function pointer variables/parameters are declared as:

    typeOfReturnValue (*fname)(typeOfArguments)

  • 8/10/2019 Lecture 1 Introduction Linked Lists Function Pointers

    20/28

    EXAMPLE OF FUNCTION POINTERS

    int square(int x){ return x*x;}

    int timesTwo(int x){return x*2;}

    int (*fp)(int);

    fp = □ //fp points to the square function

    int n = (*fp)(10); //call the square function with input 10

    fp = timesTwo; //works without the &

    //fp points to the timesTwo function

    n = (*fp)(2); //call the timesTwo function with input 2

    n = fp(2); //can also use normal function call

    //notation

    riable called fp here, and its a function pointer, which is only allowed to point to functions that have input/output that are in

    //give fp the address of square

    (pass in value of 10 into functio

    ways of calling the function

  • 8/10/2019 Lecture 1 Introduction Linked Lists Function Pointers

    21/28

    #include

    intmystery(inta,intb,int(*fn)(int,int)){

    return((*fn)(a,b));

    }

    intgcd(inta,intb){

    intc;

    while(a !=0){

    c =a;

    a =b%a;

    b =c;

    }

    returnb;

    }

    intsumofsquares(intx,inty){

    return(x*x +y*y);

    }

    intsum(intx,inty){

    return(x +y);

    }intmain(){

    intn =mystery(8,12,sum);

    printf("%d \n",n);

    printf("%d \n",mystery(8,12,gcd));

    printf("%d \n",mystery(8,12,sumofsquares));

    return0;

    }

    inputs for mystery: int int and function pointer

    takes function fn, and runs in by passing in a and b

    first, executes sum(a,b)then gcf(a,b)

    then sumofsquares(a,b)

    point to a function

    by using a variable

    and then call the

    function through the

    variable

    mystery.c

  • 8/10/2019 Lecture 1 Introduction Linked Lists Function Pointers

    22/28

    #include

    voidprintSomething(intx){

    printf("%d\n",x);

    }

    intsquare(intx){

    returnx*x;

    }

    intabsVal(intx){

    if(x

  • 8/10/2019 Lecture 1 Introduction Linked Lists Function Pointers

    23/28

    FUNCTION POINTERS

    Higher-order functions: functions that get other

    functions as arguments, or return functions as a result

    Example: the function traverse takes a list and a

    function pointer as argument, and applies to function toall nodes in the list

    void printList(link ls){

    link curr = ls;

    while(curr != NULL){

    printf(%d ,curr->data); //Process the node

    curr = curr->next;

    }

    }

    // apply function f to all nodes in ls

    void traverse (link ls, void (*f) (link)){

    link curr = ls;

    while(curr != NULL){

    (*f) (curr);

    curr = curr->next;

    }

    }

    //set curr to beginning of list

    //move to next node

    //print the data in the node

    //general traversal function, it doesn't know what we're gonna do with the

    //it runs the function f, but it doesnt know what the function does

    // passes in curr, then moves to next node

    function f only runs on a pointer to one of the nodes

    & the function must fit this prototype

  • 8/10/2019 Lecture 1 Introduction Linked Lists Function Pointers

    24/28

    USING FUNCTION POINTERSvoid printNode(link ls){

    if(ls != NULL){

    printf("%d->",ls->data);

    }

    }

    void printGrade(link ls){

    if(ls != NULL){if(ls->data>= 85){

    printf("HD ");

    } else {

    printf("FL ");

    }

    }

    }

    // apply function f to all nodes in ls

    void traverse (link ls, void (*f) (link)){ //f must have prototype void f(link)

    link curr = ls;

    while(curr != NULL){

    (*f) (curr);curr = curr->next;

    }

    }

    //To call the function

    traverse(myList,printNode); //function passed in must have the right prototype

    traverse(myList,printGrade);

    //posibillities for functions that traverse can call

    //process the data, and if its larger or equal to 85, it prints HD, else prints FL

    //print the data

    //function must have the correct prototype

  • 8/10/2019 Lecture 1 Introduction Linked Lists Function Pointers

    25/28

    typedefintItem;

    typedefstructnode *link;

    structnode{

    Item item;

    link next;

    };

    voidmultByTwo(link ls);

    voiddivideByTwo(link ls);

    voidprintList(link list);

    link newList();

    link newNode(Item item);

    link insertEnd(link list,link n);link insertFront(link list,link n);

    link deleteFirstItem(link list);

    voiddeleteNext(link curr);

    // These functions were created to demonstrate the

    // use of function pointers

    voidtraverse(link ls,void(*visit)(link));

    voidtraverseIf(link ls,void(*visit)(link),int(*f)

    (Item));

    //int (*f) (Item)

    intisNegative(Item item);

    intisOdd(Item item);

    intisFail(Item item);

    //void (*visit) (link)

    voidprintGrade(link ls);

    voidprintNode(link ls);

    voidprintValue(link ls);

    WHAT DOES THIS CODE DO

    see useList.c

    lists.h

  • 8/10/2019 Lecture 1 Introduction Linked Lists Function Pointers

    26/28

    #include

    #include

    #include "lists.h"

    intmain(intargc,constchar*argv[]){

    inti;

    link myList =newList();

    for(i=-9;i

  • 8/10/2019 Lecture 1 Introduction Linked Lists Function Pointers

    27/28

    #include

    #include

    #include "lists.h"

    voidprintList(link list){

    link curr;

    for(curr =list;curr !=NULL;curr=curr->next){

    printf("%d ",curr->item);

    }

    printf("\n");

    }

    link newList(){

    returnNULL;

    }

    link newNode(Item item){

    link n =(link)malloc(sizeof(*n));

    n->item =item;

    n->next =NULL;returnn;

    }

    //O(n)

    link insertEnd(link list,link n){

    link curr;

    if(list ==NULL){

    list =n;

    }else{

    for(curr =list;curr->next !=NULL;curr =curr->next){

    }

    curr->next =n;

    }

    returnlist;

    }

    //O(1)

    link insertFront(link list,link n){

    n->next =list;

    returnn;

    }

    // These functions were created to demonstrate the use of function pointers

    voidprintValue(link ls){

    if(ls !=NULL){

    printf("%d ",ls->item);}

    }

    voidprintNode(link ls){

    if(ls !=NULL){

    printf("%d->",ls->item);

    }

    }

    lists.c

    file with all the function implementation (page 1 of 2)

    CONTINUED

  • 8/10/2019 Lecture 1 Introduction Linked Lists Function Pointers

    28/28