Pointers (additional material)

77
Pointers (additional material) 1 Department of Computer Science-BGU 00:43:55

description

Pointers (additional material). Array of pointers. Problem : Write program that receive strings from a user and print these strings in a lexicography order. Solution : Array of pointers to char (malloc) char * names[256] or char ** names; This is not the same declaration !!. - PowerPoint PPT Presentation

Transcript of Pointers (additional material)

Page 1: Pointers (additional material)

Pointers(additional material)

1

Department of Computer Science-BGU 22:22:12

Page 2: Pointers (additional material)

Array of pointers

Problem : Write program that receive strings from a user

and print these strings in a lexicography order.

Solution :Array of pointers to char (malloc)

char * names[256] or char ** names;

This is not the same declaration !!

22:22:12Department of Computer Science-BGU

2

Page 3: Pointers (additional material)

Array of pointers

Declaration:char ** names;int n,i;scanf(“%d”,&n);names = (char **)malloc(n * sizeof(char *));for(i=o; i<n; i++){

char[i] = (char*)malloc(256*sizeof(char));

}// bubble on the pointers !!

22:22:12Department of Computer Science-BGU

3

Page 4: Pointers (additional material)

Complete problem

We use exactly the size for the input strings.

Assuming that the strings have at most 255 letters.

We need receive a sorted array of strings from the function.

All the inputs are from the user.

22:22:12Department of Computer Science-BGU

4

Page 5: Pointers (additional material)

Complete solution

char ** sorted_list(){char ** names, temp[256], * temp2;int n, i, flag;scanf(“%d”,&n);names = (char **)malloc(n * sizeof(char *));for(i=0; i<n; i++){

gets(temp);char[i] = (char*)malloc(strlen(temp)+1);strcpy(char[i],temp); // char + i

}/* Sorting pointers by lexicography string

order */

22:22:12Department of Computer Science-BGU

5

Page 6: Pointers (additional material)

Complete solution(cont.)

// sorting do{

flag =0;for(i=0 ; i< n-1 ; i++)

// names + i , names +i+1if( strcmp(names[i],names[i+1]) >0){temp = names+i;names +i = names +i+1;names+i+1 = temp;flag = 1;}

}while(flag);return names;

}

22:22:12Department of Computer Science-BGU

6

Page 7: Pointers (additional material)

Linked Lists

22:22:12

7

Department of Computer Science-BGU

Page 8: Pointers (additional material)

Problems with dynamic arrays

Problems: Adding/ delete member. Reallocation. Building sort list . Merging .

Solution: Linked list Simple add/delete member. No need reallocation. Building sorting. Simple merging.

22:22:12

8

Department of Computer Science-BGU

Page 9: Pointers (additional material)

Linked lists?

head

NULL

Structures

22:22:12

9

Department of Computer Science-BGU

A better alternative might be using a linked list, by “self reference”.

Page 10: Pointers (additional material)

Linking students

typedef struct Student_t {char ID[ID_LENGTH];char Name[NAME_LENGTH];int grade;struct Student_t *next; /* A pointer to the next item on the list */

} item;

22:22:12

10

Department of Computer Science-BGU

Page 11: Pointers (additional material)

Different definition

A different use of typedef:

typedef struct Student_t item ;struct Student_t{

char ID[ID_LENGTH];char Name[NAME_LENGTH];int grade;item *next; /* A pointer to the next item

on the list without use of “struct” in the pointer definition */

} ;

22:22:12Department of Computer Science-BGU

11

Page 12: Pointers (additional material)

Creating a new kind of student

Usually when using linked lists we don’t know how many elements will be in the list

Therefore we would like to be able to dynamically allocate new elements when the need arises.

A possible implementation follows…

22:22:12

12

Department of Computer Science-BGU

Page 13: Pointers (additional material)

Creating a new kind of student

item*create_student(char * name, char * ID, int grade) {item *std;std = (item *)malloc(item));if (std == NULL) {

printf(“Memory allocation error!\n”);exit(1);

}strcpy(std->Name, name);strcpy(std->ID, ID);std->grade = grade;std->next = NULL;return std;

}

std

NULL

22:22:13

13

Department of Computer Science-BGU

Page 14: Pointers (additional material)

Linked lists - insertion

Head

Insert new item:

Previous

Next

22:22:13

14

Department of Computer Science-BGU

Page 15: Pointers (additional material)

Linked lists - insertion

Head

Insert new item:

Previous

Next

22:22:13

15

Department of Computer Science-BGU

Page 16: Pointers (additional material)

Linked lists - insertion

Head

Insert new item:

Previous

Next

22:22:13

16

Department of Computer Science-BGU

Page 17: Pointers (additional material)

Adds a new item to the end of the list

head NULL

newItem

NULL

22:22:13

17

Department of Computer Science-BGU

Page 18: Pointers (additional material)

Adds a new item to the end of the list

newItem

NULLhead

22:22:13

18

Department of Computer Science-BGU

Page 19: Pointers (additional material)

Adds a new item to the end of the list

NULL

head

22:22:13

19

Department of Computer Science-BGU

Page 20: Pointers (additional material)

Adds a new item to the end of the list

head

NULL

newItem

NULL

currItem

22:22:13

20

Department of Computer Science-BGU

Page 21: Pointers (additional material)

Adds a new item to the end of the list

head

NULL

newItem

NULL

currItem

22:22:13

21

Department of Computer Science-BGU

Page 22: Pointers (additional material)

Adds a new item to the end of the list

head

NULL

newItem

NULL

currItem

22:22:13

22

Department of Computer Science-BGU

Page 23: Pointers (additional material)

Adds a new item to the end of the list

head

NULL

newItem

NULL

currItem

22:22:13

23

Department of Computer Science-BGU

Page 24: Pointers (additional material)

Adds a new item to the end of the list

head

NULL

newItem

NULL

currItem

22:22:13

24

Department of Computer Science-BGU

Page 25: Pointers (additional material)

Adds a new item to the end of the list

 item * add_last(item *head, item* newItem){item *currItem;if (!head)

return newItem;currItem = head;while(currItem->next)

currItem = currItem->next;currItem->next = newItem; 

return head;}  

22:22:13

25

Department of Computer Science-BGU

Page 26: Pointers (additional material)

Inserts into a sorted list

head NULL

newItem

NULL

22:22:13

26

Department of Computer Science-BGU

Page 27: Pointers (additional material)

Inserts into a sorted list

newItem

NULLhead

22:22:13

27

Department of Computer Science-BGU

Page 28: Pointers (additional material)

Inserts into a sorted list

NULL

head

22:22:13

28

Department of Computer Science-BGU

Page 29: Pointers (additional material)

Inserts into a sorted list

8 28

head

NULL16

5

newItem

NULL

22:22:13

29

Department of Computer Science-BGU

Page 30: Pointers (additional material)

Inserts into a sorted list

8 28

head

NULL16

5

newItem

NULL

22:22:13

30

Department of Computer Science-BGU

Page 31: Pointers (additional material)

Inserts into a sorted list

8 28

head

NULL16

5

newItem

22:22:13

31

Department of Computer Science-BGU

Page 32: Pointers (additional material)

Inserts into a sorted list

8 28

head

NULL16

20

newItem

NULL

22:22:13

32

Department of Computer Science-BGU

Page 33: Pointers (additional material)

Inserts into a sorted list

8 28

head

NULL16

20

newItem

NULL

currItem

22:22:13

33

Department of Computer Science-BGU

Page 34: Pointers (additional material)

Inserts into a sorted list

8 28

head

NULL16

20

newItem

NULL

currItem

22:22:13

34

Department of Computer Science-BGU

Page 35: Pointers (additional material)

Inserts into a sorted list

8 28

head

NULL16

20

newItem

NULL

currItem

22:22:13

35

Department of Computer Science-BGU

Page 36: Pointers (additional material)

Inserts into a sorted list

// while keeping it sorted ascending by keyitem * insert(item *head, item *newNode) {  item *currItem;  if (!head) return newNode; //check if newNode's key is smaller than all keys and should be first

if (newNode->key < head->key) { newNode->next = head; return newNode; } currItem = head; while (currItem->next && newNode->key > currItem->next->key)

currItem = currItem->next;//put newNode between currItem and currItem->next //(if currItem is last then currItem->next == NULL) newNode->next = currItem->next; currItem->next = newNode; return head;}   

22:22:14

36

Department of Computer Science-BGU

Page 37: Pointers (additional material)

Linked lists - searching

head?currItem

22:22:14

37

Department of Computer Science-BGU

Page 38: Pointers (additional material)

Linked lists - searching

head?currItem

22:22:14

38

Department of Computer Science-BGU

Page 39: Pointers (additional material)

Linked lists - searching

head?currItem

!

22:22:14

39

Department of Computer Science-BGU

Page 40: Pointers (additional material)

Searching for an item

 //searches for an item with passed key.//returns NULL if didn't find it.item *search(item *head, int key) {

item *currItem = head; if (!head) return NULL;while (currItem) { //loop through the list

if (currItem->key == key)return currItem;

currItem = currItem->next;}  //didn't find the item with the requested keyreturn NULL;

22:22:14

40

Department of Computer Science-BGU

Page 41: Pointers (additional material)

Print list’s members

//prints keys of items of the list, key after key.void printKeys(item *head) {

item *curr = head; while (curr) {

printf("%d ", curr->key);curr = curr->next;

}putchar('\n');

}

22:22:14

41

Department of Computer Science-BGU

Page 42: Pointers (additional material)

Linked lists - delete

Head

Structure to delete

22:22:14

42

Department of Computer Science-BGU

Page 43: Pointers (additional material)

Linked lists - delete

Head

Current

22:22:14

43

Department of Computer Science-BGU

Previous

NULL

Structure to delete

Page 44: Pointers (additional material)

Linked lists - delete

HeadPreviou

sCurrent

22:22:14

44

Department of Computer Science-BGU

Structure to delete

Page 45: Pointers (additional material)

Linked lists - delete

HeadPreviou

sCurrent

22:22:14

45

Department of Computer Science-BGU

Structure to delete

Page 46: Pointers (additional material)

Linked lists - delete

HeadPreviou

sCurrent

22:22:14

46

Department of Computer Science-BGU

Page 47: Pointers (additional material)

Linked lists - delete

HeadPreviou

sCurrent

22:22:14

47

Department of Computer Science-BGU

Page 48: Pointers (additional material)

Linked lists - delete

HeadPreviou

s

22:22:14

48

Department of Computer Science-BGU

Page 49: Pointers (additional material)

Remove the item with a given value

item *remove(int value, item* head){item * curr= head,*prev=NULL;int found=0;if(!head)

printf("The LL is empty\n");else{

while(curr)if(value==curr->value){

prev ?prev->next=curr->next:head=head->next;free(curr);found=1;break;

}else{

prev=curr;curr=curr->next;

}if(!found) printf("The record with key %d was not found\

n",value);}

return head;}

22:22:14

49

Department of Computer Science-BGU

Page 50: Pointers (additional material)

Freeing students

After we’re done, we need to free the memory we’ve allocated

One implementation is as we saw in class

void free_list(Student *head){

Student *to_free = head;

while (to_free != NULL) {

head = head->next;free(to_free);to_free = head;

}}

22:22:15

50

Department of Computer Science-BGU

Page 51: Pointers (additional material)

Recursive freeing

A perhaps simpler way to free a list is recursively.

void free_list(Student *head){

if (head== NULL) /* Finished freeing. Empty list */return;

free_list(head->next); /* Recursively free what’s ahead */free(head);

}

22:22:15

51

Department of Computer Science-BGU

Page 52: Pointers (additional material)

Split linked list

typedef struct stam item;struct stam{

int value;item * next;

}void main(){

item * head=*odd=*even = NULL;//// /* build list */// Now split it in two lists with odd and even membersvoid Split(head, odd, even);print_list(odd);print_list(even);

}

22:22:15Department of Computer Science-BGU

52

Page 53: Pointers (additional material)

Split linked list

// Split the nodes to these 'a' and 'b' listsvoid Split(item * source, item * od, item * ev) {

item * current = source, * temp;while (current != NULL) {

temp = current;if(temp->value %2 != 0)od = add_last(od,current);else ev = add_last(ev,current);current = current -> next;temp->next = NULL;

}}

22:22:15Department of Computer Science-BGU

53

Page 54: Pointers (additional material)

Split linked list

typedef struct stam item;struct stam{

int value;item * next;

}void main(){

item * head=*odd=*even = NULL;//// /* build list */// Now split it in two lists with odd and even membersvoid Split(head, &odd, &even);print_list(odd);print_list(even);

}

22:22:15Department of Computer Science-BGU

54

Page 55: Pointers (additional material)

Split linked list

void Split(item * source, item ** od, item ** ev) {item * current = source;item * a =*b = NULL;while (current != NULL) {

temp = current;if(temp->value %2 != 0)

a = add_last(a,current);else b = add_last(b,current);current = current -> next;temp->next = NULL;

}*od = a;*ev = b;

}

22:22:15Department of Computer Science-BGU

55

Page 56: Pointers (additional material)

(stackהמחסנית )

22:22:15Department of Computer Science-BGU

מחסנית - הינה מבנה נתונים מופשט. התכונה העיקרית שלה היא 56שהאיבר הראשון שיוכנס אליה יהיה

) - כלומר הוצאה והכנסה של איבר first in last outהראשון לצאת (אפשרית רק מלמעלה (מראש המחסנית).

ראש המחסנית הוא האיבר העליון. הפעולות:

push.דחיפת איבר לראש המחסנית - pop.(שליפת ראש המחסנית) שליפת איבר מראש המחסנית - init אתחול המחסנית,האיבר הראשון של המחסנית שווה ל - NULL

נממש את המחסנית באמצעות רשימה שבה כל פעולות ההכנסה וההוצאה מתבצעות בקצה אחד בלבד.

המחסנית הינה רשימה שהפעולות של הכנסת איברים והוצאתם נעשית בכיוון אחד ולכן מבנהו של המחסנית זהה לשל הרשימה (רק

על מנת שהדבר list ולא stackכאן אנו נגדיר ששמו של המבנה הוא יהיה ברור).

Page 57: Pointers (additional material)

מבנה כללי של המחסנית

typedef DATA ...struct stack { DATA data; struct stack *next;}; 

 

22:22:15Department of Computer Science-BGU

57

Page 58: Pointers (additional material)

)(pushהכנסת איבר לראש המחסנית -

 

void push (struct stack** head, DATA data){ struct stack* second = *head; *head = (struct stack*)malloc(sizeof(struct stack)); (*head)->data = data; (*head)->next = second;}

22:22:15Department of Computer Science-BGU

58

Page 59: Pointers (additional material)

)(pop :הוצאת איבר מראש המחסנית -

DATA pop (struct stack** head){DATA data = NO_ELEMENT_DATA;

if (*head == NULL) { printf ("\n can't pop from empty stack\n"); } else { struct stack *temp = *head; *head = (*head)->next;

data = temp->data; free(temp); }

return data;}

22:22:15Department of Computer Science-BGU

59

Page 60: Pointers (additional material)

22:22:15Department of Computer Science-BGU 60

void main)({DATA val;int op;struct stack * stack = NULL;do{

printf)"\n enter 1 for push 2 for pop. 0 to quit "(;scanf)"%d",&op(;if ) op==1({

printf)"\n enter value: "(;scanf)"%d",&val(;push)&stack, val(;

}else if )op == 2( {

if )!is_empty)stack(( {val = pop)&stack(;printf)"\n poped %d", val(;

}else{

printf )"\n can't pop from empty stack\n"(;}

}}while)op(;while )! is_empty)stack( (

pop)&stack(; // emptying the stack}

Page 61: Pointers (additional material)

איתחול של מחסנית

void init_stack (struct stack** head){ *head = NULL;} 

int is_empty(struct stack* stack){return (!stack);

22:22:15Department of Computer Science-BGU

61

Page 62: Pointers (additional material)

Split linked list

// Split the nodes to these 'a' and 'b' listsvoid Split(item * source, item ** od , item ** ev) {

item * a = NULL; item * b = NULL;item * current = source;while (current != NULL) {

MoveItem(&a, &current); // Move a node to 'a'if (current != NULL) { MoveItem(&b, &current); // Move a node to 'b'{

{*od= a;*ev = b;

{

22:22:15Department of Computer Science-BGU

62

Page 63: Pointers (additional material)

תור

:הפעולותappend.הוספת איבר לתור - Remove.סילוק איבר מהתור -

init.אתחול התור -

נממש את התור באמצעות רשימה שבה כל פעולות ההכנסה מתבצעת דרך קצה אחד ופעולת ההוצאה מתבצעות דרך הקצה האחר.

22:22:16Department of Computer Science-BGU

63

מבנה נתונים מופשט. תכונתו העיקרית היא הכנסה והוצאה של איברים דרך התאים שבקצוות -הכנסה של

האיברים דרך קצה אחד והוצאתם דרך הקצה האחר.

Page 64: Pointers (additional material)

Initialize

22:22:16Department of Computer Science-BGU

64

struct queue {    int num;    struct queue *next;};

void init_queue (struct queue** que){    *que = NULL;}

Page 65: Pointers (additional material)

Append

void append (struct queue** que, int num){    static struct queue* last;    static struct queue* n_last;

    n_last = (struct queue*)malloc(sizeof(struct queue));    n_last->num = num;    n_last->next =NULL;    if (*que == NULL)        *que = n_last;    else        last->next = n_last;    last = n_last;}

22:22:16Department of Computer Science-BGU

65

Page 66: Pointers (additional material)

Display

void display_queue (struct queue* que){    struct queue* temp = que;    printf ("\nThe members of the queue are: \n\n");    while (temp != NULL)    {        printf (" %d ", temp->num);        temp = temp->next;    }    temp = que;    printf("\n");    while (temp != NULL)    {        printf ("%p ", temp);        temp = temp->next;    }}

22:22:16Department of Computer Science-BGU

66

Page 67: Pointers (additional material)

Delete

void delete_queue (struct queue** que){    struct queue *temp;

    printf("\n\nDeleting the queue:\n");    while (*que)    {        printf ("%p\t", *que);        temp = *que;        *que = (*que)->next;        free(temp);

    }}

22:22:16Department of Computer Science-BGU

67

Page 68: Pointers (additional material)

void main(){    struct queue* que;    randomize();

    init_queue (&que);    build_queue (&que);    display_queue (que);    delete_queue (&que);}

22:22:16Department of Computer Science-BGU

68

Page 69: Pointers (additional material)

Building

void build_queue (struct queue** que){    int i, num;

    printf ("\nThe number by their insertion order are:\n");    for (i = 0; i < MAX; i++)    {        num = random(10);        append (que, num);    }}

22:22:16Department of Computer Science-BGU

69

Page 70: Pointers (additional material)

1 שאלה

מקבלת את העוגן של רשימה משורשרת רגילה singleפונקצית head הפונקציה משחררת מהרשימה את כל המבנים שהערך שבהם ,

הופיע מקודם ברשימה. (הפונקציה משאירה כל ערך פעם אחת ברשימה).

הקטעים המסומנים ב- ?? ?? כך 7השלם בדפי התשובות את שהפונקציה תבצע את הנדרש.

typedef struct item item;

struct item{int value;

item *next;};

22:22:17Department of Computer Science-BGU

70

Page 71: Pointers (additional material)

22:22:17Department of Computer Science-BGU 71

item * single(item *head){item *prev, *temp;while( head ){

prev = head;temp = head -> next;while( temp )

if( ?? 1 ?? ){?? 2 ?? = temp -> next;free( ?? 3 ?? );temp = ?? 4 ?? ;

}else}

prev = ?? 5 ?? ;temp = ?? 6 ?? ;

}?? 7 ?? ;

}}

 ?? 1 ?? temp->value == head->value?? 2 ?? prev->next ?? 3 ?? temp?? 4 ?? prev->next?? 5 ?? temp

or prev->next?? 6 ?? temp->next

or prev->next?? 7 ?? head = head_next;

Page 72: Pointers (additional material)

2שאלה

נתונות ההגדרה והפונקציות הבאות:

typedef struct item item;struct item{

int value; item *next;

};

22:22:17Department of Computer Science-BGU

72

Page 73: Pointers (additional material)

item* what2(item* p1, item* p2){item *temp;if(!p1) return p2;temp = p1 -> next;p1 -> next = p2;return what2(temp, p1);

}item* what1(item* p){

if(!p) return NULL;return what2(p, NULL);

}

22:22:18Department of Computer Science-BGU

73

Page 74: Pointers (additional material)

22:22:18Department of Computer Science-BGU

74

?what2מה יעודה של הפונקציה • ?what1מה יעודה של הפונקציה • הוא העוגן של הרשימה המקושרת, על מה מצביע list כאשר•

what1(list).צייר את מבנה הנתונים המתקבל ,

Page 75: Pointers (additional material)

פתרון

.אwhat2-הופכת את הרשימה המשורשרת שמתחילה ב p1 p2ומחברת אותה ל-

.בwhat1הופכת רשימה ומחזירה את העוגן החדש .ג

what1(list) 4216537908 NULL

22:22:18Department of Computer Science-BGU

75

Page 76: Pointers (additional material)

נתונה ההגדרה הבאה של מבנה ברשימה משורשרת:typedef struct node{

int val;struct node *next;

} node;

node* odd_even(node* head) הלא רקורסיביתהפונקציה מצביע לראש רשימה מקושרת ומסדרת מחדש את headמקבלת כארגומנט

) יופיעו ראשונים (באותו oddהרשימה כך שהאיברים בעלי ערך אי-זוגי () יופיעו לאחר מכן (באותו הסדר).evenהסדר) והאיברים בעלי ערך זוגי (

הפונקציה מחזירה את ראש הרשימה החדשה.

 

) בפונקציה הבאה: ?? N?? השלם את הקטעים החסרים (המסומנים ב -

22:22:18Department of Computer Science-BGU

76

Page 77: Pointers (additional material)

22:22:18Department of Computer Science-BGU 77

node* odd_even)node* head({node *even = NULL, *odd = NULL;node *headEven = NULL, *headOdd=NULL;

  while )head({if)head->val % 2({

if) ?? 1 ?? (?? 2 ??;

else?? 3 ??;

odd = ?? 4 ??;}else{

if)?? 5 ??( ?? 6 ?? ;else ?? 7 ?? ;?? 8 ?? ;

}?? 9 ?? ;

}if)!odd( ?? 10 ?? ;if)!even( ?? 11 ?? ;

 odd ->next = ?? 12 ?? ;even->next = ?? 13 ??;

  return ?? 14 ??;}

?? 1 ?? = odd?? 2 ?? = odd->next = head?? 3 ?? = headOdd = head?? 4 ?? = head?? 5 ?? = even?? 6 ?? = even->next = head?? 7 ?? = headEven = head?? 8 ?? = even = head?? 9 ?? = head = head->next?? 10 ?? = return headEven?? 11 ?? = return headOdd?? 12 ?? = headEven?? 13 ?? = NULL?? 14 ?? = headOdd