programming n.
Download
Skip this Video
Loading SlideShow in 5 Seconds..
Programming PowerPoint Presentation
Download Presentation
Programming

Loading in 2 Seconds...

play fullscreen
1 / 70

Programming - PowerPoint PPT Presentation


  • 75 Views
  • Uploaded on

Programming. Linked Lists. Linked Lists. Dynamic Efficient use of memory Allocate just as much as needed Easy insertion in front Local deletion But… Hard to get to any particular element. Data. Data. Data. Next. Next. Next. Linked Lists. A list is a chain of nodes.

loader
I am the owner, or an agent authorized to act on behalf of the owner, of the copyrighted work described.
capcha
Download Presentation

PowerPoint Slideshow about 'Programming' - marion


An Image/Link below is provided (as is) to download presentation

Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author.While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server.


- - - - - - - - - - - - - - - - - - - - - - - - - - E N D - - - - - - - - - - - - - - - - - - - - - - - - - -
Presentation Transcript
programming

Programming

Linked Lists

linked lists
Linked Lists
  • Dynamic
  • Efficient use of memory
    • Allocate just as much as needed
  • Easy insertion in front
  • Local deletion

But…

  • Hard to get to any particular element
linked lists1

Data

Data

Data

Next

Next

Next

Linked Lists
  • A list is a chain of nodes.

typedefstruct node_type{ <data>struct node_type* next;} Node;

head

NULL

linked lists operations
Linked Lists Operations
  • Insert
    • front, back, middle
  • Delete
  • Find
  • Size
course management system
Course Management System
  • Maintain a list of students
    • Keep their ID, name, grade etc.
  • Allow for adding / removing a student
  • Find a student in the list
  • Produce Reports
    • For example: Average grade
storing a collection of students
Storing a Collection of Students

Suggestion 1

Use an array of student structures

  • Problems:
    • What size is the array?
    • Remove students – either expensive or creates “holes”
    • Insertion in a sorted array is expensive

“holes”:

linking students
Linking Students

Suggestion 2

Use a linked list

Define a student node:

typedef struct student {

char id[ID_LENGTH];

char name[NAME_LENGTH];

int grade;

/* A pointer to the next node in the list */

struct student *next;

} sStudent;

exercise
Exercise
  • Download find_student_ex.c from the tirgul home page
  • Implement:

sStudent* find_student(const sStudent *head, const char* id)

  • find_student searches for a student with a given id. It returns a pointer to the student if found, otherwise it returns NULL.
creating a new student
Creating a New Student

sStudent* new_student(char* name, char* id,

int grade)

{

sStudent *std =(sStudent*)malloc(sizeof(sStudent));

if (std != NULL) {

strcpy(std->name, name);

strcpy(std->id, id);

std->grade = grade;

std->next = NULL;

}

return std;

}

add in front
Add in Front

sStudent* add_front(sStudent *head, sStudent *std){ std->next = head;return std;}int main(){ sStudent *std_list, *std; ... std = new_student(...);

if (std != NULL )

std_list = add_front(std_list, std);

...

return 0;}

sorted add
Sorted Add
  • If the list is sorted (for example by grade), a student insertion should keep the list sorted
  • We will implement this in a separate function
adding a student mid end
Adding a student – mid/end

Previous

Next

Head

Insert new item:

slide14
sStudent *add_student(sStudent *head, sStudent *to_add)

{

sStudent *curr_std, *prev_std = NULL;

if (head == NULL)

return to_add;if (to_add->grade > head->grade)

{

to_add->next = head;

return to_add;

}

curr_std = head;

while (curr_std != NULL && to_add->grade < curr_std->grade)

{

prev_std = curr_std;

curr_std = curr_std->next;

}

prev_std->next = to_add;

to_add->next = curr_std;

return head;}

handle empty list

handle beginning

the rest

adding a student beginning
Adding a student – beginning

if (head == NULL)

return to_add;

if (to_add->grade > head->grade)

{

to_add->next = head;

return to_add;

}

95

80

70

head

to_add

100

adding a student mid end1
Adding a student – mid / end

curr_std = head;

while (curr_std != NULL && to_add->grade < curr_std->grade)

{

prev_std = curr_std;

curr_std = curr_std->next;

}

prev_std->next = to_add;

to_add->next = curr_std;

return head;

curr_std

95

80

70

60

head

to_add

75

adding a student mid end2
Adding a student – mid / end

curr_std = head;

while (curr_std != NULL && to_add->grade < curr_std->grade)

{

prev_std = curr_std;

curr_std = curr_std->next;

}

prev_std->next = to_add;

to_add->next = curr_std;

return head;

curr_std

95

80

70

60

head

to_add

75

adding a student mid end3
Adding a student – mid / end

curr_std = head;

while (curr_std != NULL && to_add->grade < curr_std->grade)

{

prev_std = curr_std;

curr_std = curr_std->next;

}

prev_std->next = to_add;

to_add->next = curr_std;

return head;

prev_std

curr_std

95

80

70

60

head

to_add

75

adding a student mid end4
Adding a student – mid / end

curr_std = head;

while (curr_std != NULL && to_add->grade < curr_std->grade)

{

prev_std = curr_std;

curr_std = curr_std->next;

}

prev_std->next = to_add;

to_add->next = curr_std;

return head;

prev_std

curr_std

95

80

70

60

head

to_add

75

adding a student mid end5
Adding a student – mid / end

curr_std = head;

while (curr_std != NULL && to_add->grade < curr_std->grade)

{

prev_std = curr_std;

curr_std = curr_std->next;

}

prev_std->next = to_add;

to_add->next = curr_std;

return head;

prev_std

curr_std

95

80

70

60

head

to_add

75

adding a student mid end6
Adding a student – mid / end

curr_std = head;

while (curr_std != NULL && to_add->grade < curr_std->grade)

{

prev_std = curr_std;

curr_std = curr_std->next;

}

prev_std->next = to_add;

to_add->next = curr_std;

return head;

prev_std

curr_std

95

80

70

60

head

to_add

75

adding a student mid end7
Adding a student – mid / end

curr_std = head;

while (curr_std != NULL && to_add->grade < curr_std->grade)

{

prev_std = curr_std;

curr_std = curr_std->next;

}

prev_std->next = to_add;

to_add->next = curr_std;

return head;

prev_std

curr_std

95

80

70

60

head

to_add

75

adding a student mid end8
Adding a student – mid / end

curr_std = head;

while (curr_std != NULL && to_add->grade < curr_std->grade)

{

prev_std = curr_std;

curr_std = curr_std->next;

}

prev_std->next = to_add;

to_add->next = curr_std;

return head;

prev_std

curr_std

95

80

70

60

head

to_add

75

adding a student mid end9
Adding a student – mid / end

curr_std = head;

while (curr_std != NULL && to_add->grade < curr_std->grade)

{

prev_std = curr_std;

curr_std = curr_std->next;

}

prev_std->next = to_add;

to_add->next = curr_std;

return head;

prev_std

curr_std

95

80

70

60

head

to_add

75

adding a student mid end10
Adding a student – mid / end

curr_std = head;

while (curr_std != NULL && to_add->grade < curr_std->grade)

{

prev_std = curr_std;

curr_std = curr_std->next;

}

prev_std->next = to_add;

to_add->next = curr_std;

return head;

prev_std

curr_std

95

80

70

60

head

to_add

75

removing a student
Removing a student
  • We would like to be able to remove a student by her/his ID.
  • The function that performs this is remove_student
removing a student reminder
Removing a student - reminder

Previous

Current

Head

removing a student beginning
Removing a student – beginning

if (head == NULL) return head;

cur = head;

if (strcmp(cur->id, id) == 0)

{

head = head->next;

free(cur);

return head;

}

ID

14525

cur

14525

74823

53621

25773

head

removing a student mid list
Removing a student – mid list

ID

while (cur != NULL && strcmp(cur->id, id) != 0)

{

prev = cur;

cur = cur->next;

}

if (cur != NULL){

prev->next = cur->next;

free(cur);}

return head;

53621

cur

14525

74823

53621

25773

head

removing a student mid list1
Removing a student – mid list

ID

while (cur != NULL && strcmp(cur->id, id) != 0)

{

prev = cur;

cur = cur->next;

}

if (cur != NULL){

prev->next = cur->next;

free(cur);}

return head;

53621

prev

cur

14525

74823

53621

25773

head

removing a student mid list2
Removing a student – mid list

ID

while (cur != NULL && strcmp(cur->id, id) != 0)

{

prev = cur;

cur = cur->next;

}

if (cur != NULL){

prev->next = cur->next;

free(cur);}

return head;

53621

prev

cur

14525

74823

53621

25773

head

removing a student mid list3
Removing a student – mid list

ID

while (cur != NULL && strcmp(cur->id, id) != 0)

{

prev = cur;

cur = cur->next;

}

if (cur != NULL){

prev->next = cur->next;

free(cur);}

return head;

53621

prev

cur

14525

74823

53621

25773

head

removing a student mid list4
Removing a student – mid list

while (cur != NULL && strcmp(cur->id, id) != 0)

{

prev = cur;

cur = cur->next;

}

if (cur != NULL){

prev->next = cur->next;

free(cur);}

return head;

ID

53621

prev

cur

14525

74823

25773

head

deallocating all students
Deallocating all students

void free_list(sStudent *head)

{

sStudent *temp = head;

while (head != NULL)

{ temp = head;

head = head->next;

free(temp);

}

}

deallocating students
Deallocating students

while (head != NULL)

{ temp = head;

head = head->next;

free(temp);

}

temp

head

deallocating students1
Deallocating students

while (head != NULL)

{ temp = head;

head = head->next;

free(temp);

}

temp

head

deallocating students2
Deallocating students

while (head != NULL)

{temp = head;

head = head->next;

free(temp);

}

temp

head

deallocating students3
Deallocating students

while (head != NULL)

{ temp = head;

head = head->next;

free(temp);

}

temp

head

deallocating students4
Deallocating students

while (head != NULL)

{ temp = head;

head = head->next;

free(temp);

}

temp

head

deallocating students5
Deallocating students

while (head != NULL)

{ temp = head;

head = head->next;

free(temp);

}

temp

head

deallocating students6
Deallocating students

while (head != NULL)

{temp = head;

head = head->next;

free(temp);

}

temp

head

deallocating students7
Deallocating students

while (head != NULL)

{ temp = head;

head = head->next;

free(temp);

}

temp

head

deallocating students8
Deallocating students

while (head != NULL)

{ temp = head;

head = head->next;

free(temp);

}

temp

head

deallocating students9
Deallocating students

while (head != NULL)

{ temp = head;

head = head->next;

free(temp);

}

temp

head

deallocating students10
Deallocating students

while (head != NULL)

{temp = head;

head = head->next;

free(temp);

}

temp

head

deallocating students11
Deallocating students

while (head != NULL)

{ temp = head;

head = head->next;

free(temp);

}

temp

head

deallocating students12
Deallocating students

while (head != NULL)

{ temp = head;

head = head->next;

free(temp);

}

temp

head

deallocating students13
Deallocating students

while (head != NULL)

{ temp = head;

head = head->next;

free(temp);

}

temp

head

deallocating students14
Deallocating students

while (head != NULL)

{temp = head;

head = head->next;

free(temp);

}

temp

head

deallocating students15
Deallocating students

while (head != NULL)

{ temp = head;

head = head->next;

free(temp);

}

temp

head

deallocating students16
Deallocating students

while (head != NULL)

{ temp = head;

head = head->next;

free(temp);

}

temp

head

deallocating students17
Deallocating students

while (head != NULL)

{ temp = head;

head = head->next;

free(temp);

}

temp

head

NULL

deallocating students18
Deallocating students

void free_list(sStudent *head)

{

if (head == NULL)

return;

free_list(head->next);

free(head);

}

reverse list
Reverse List

Input:

Output:

recursive reverse code
Recursive Reverse - Code

Node * reverse_iter(Node * prev, Node* curr)

{

Node * tmp;

if (curr == NULL)

returnprev;

tmp = curr->next; // keep a link to the rest of the list

curr->next = prev; // change direction of current node

returnreverse_iter(curr, tmp); // reverse the rest of the list

}

Node * reverse(Node * head)

}

returnreverse_iter(NULL, head);

{

slide57

push(2)

push(3)

pop()

מצב המחסנית

מצב המחסנית

מצב המחסנית

מצב המחסנית

ריק

2

3

2

2

שאלה 3, סמסטר א' תש"ע, מועד ב'

מחסנית היא מבנה נתונים שבו הערך שנכנס ראשון יוצא אחרון.

נגדיר שתי פעולות על המחסנית:

push - מכניסה ערך לראש המחסנית.

pop - מוציאה את הערך העליון מהמחסנית ומחזירה אותו.

דוגמא: push(2), push(3) ן-pop() על מחסנית ריקה

slide58
שאלה 3, סמסטר א' תש"ע, מועד ב'

נממש מחסנית של מספרים שלמים בעזרת רשימה מקושרת.

הגדרת המחסנית:

typedef struct stack_t

{

int size;

Element *head;

} Stack;

slide59
שאלה 3, סמסטר א' תש"ע, מועד ב'

יצירת מחסנית חדשה:

Stack * createStack()

{

Stack *s = (Stack*) malloc(sizeof(Stack));

if (s != NULL)

{

s->size = 0;

s->head = NULL;

}

return s;

}

slide60
שאלה 3, סמסטר א' תש"ע, מועד ב'

יצירת איבר ברשימה:

Element * createElement(int data)

{

Element *e = (Element*) malloc(sizeof(Element));

if (e != NULL)

{

e->data = data;

e->next = NULL;

}

return e;

}

מה השדות של המבנה Element?

מה השדות של המבנה Element?

slide61
שאלה 3, סמסטר א' תש"ע, מועד ב'

הכנסת ערך למחסנית (בתחילת הרשימה המקושרת):

void push(Stack *s, int data)

{

Element *e = createElement(data);

if (e == NULL)

{

printf("Fatal error: unable to allocate memory!\n");

exit(1);

}

e->next = s->head;

s->head = e;

s->size++;

}

slide62
שאלה 3, סמסטר א' תש"ע, מועד ב'

בדיקה האם המחסנית ריקה:

int isEmpty(Stack *s)

{

return s->size == 0;

}

סעיף א':

הגדירו את המבנה Element. ודאו כי הגדרת המבנה תואמת את השימוש שנעשה בו בפונקציות הנתונות.

slide63
שאלה 3, סמסטר א' תש"ע, מועד ב'

typedef struct element

{

int data;

struct element *next;

} Element;

slide64
שאלה 3, סמסטר א' תש"ע, מועד ב'

סעיף ב':

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

הנחת מימוש: המחסנית אינה ריקה

slide65
שאלה 3, סמסטר א' תש"ע, מועד ב'

int pop(Stack *s) // assume s is not empty

{

Element *first = s->head;

int data = first->data;

s->head = s->head->next;

s->size--;

free(first);

return data;

}

שמירת כתובת וערך

האיבר הראשון

עדכון המחסנית

שימוש בכתובת וערך

האיבר הראשון

slide66
שאלה 3, סמסטר א' תש"ע, מועד ב'

סעיף ג':

ממשו את הפונקציה stackSum.

קלט: מחסנית

פלט: סכום הערכים במחסנית תוך שימוש בפעולות שהוגדרו על המחסנית כדוגמת push, pop ו- isEmpty.

  • חל איסור על גישה לרשימת האיברים באופן ישיר.
  • לאחר הקריאה לפונקציה המחסנית תהיה ריקה.
slide67
שאלה 3, סמסטר א' תש"ע, מועד ב'

int stackSum(Stack *s)

{

int sum = 0;

while (!isEmpty(s))

sum += pop(s);

return sum;

}

slide68
שאלה 3, סמסטר א' תש"ע, מועד ב'

סעיף ד':

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

  • ניתן להניח שקלט המשתמש תקין
  • במידה והשתמשתם בהקצאת זיכרון דינמית ודאו שבוצע שיחרור של הזיכרון
  • בניקוד סעיף זה יושם דגש על אי שכפול קוד ושימוש בפונקציות שהוגדרו בסעיפים קודמים
slide69
שאלה 3, סמסטר א' תש"ע, מועד ב'

int main()

{

int val;

Stack *s = createStack();

if (s == NULL) {

printf("unable to create stack!");

return 1;

}

printf("Please enter input\n");

scanf("%d", &val);

while (val >= 0) {

push(s, val);

scanf("%d", &val);

}

printf("The sum is %d\n", stackSum(s));

free(s);

return 0;

}

solution to class exercise
Solution to Class Exercise

/* find a student whose id matches the given id */

sStudent* find_student(sStudent *head, char *id)

{

while (head != NULL) /* go over all the list */

{

if (strcmp(head->id, id) == 0) /* same id */

return head;

head = head->next;

}

/* If we're here, we didn't find it */

return NULL;

}