Upgrade to Pro — share decks privately, control downloads, hide ads and more …

CSE240 Lecture 13

CSE240 Lecture 13

Introduction to Programming Languages
Data Structures
(202009)

B546a9b97d993392e4b22b74b99b91fe?s=128

Javier Gonzalez

January 13, 2017
Tweet

Transcript

  1. jgs CSE 240 Introduction to Programming Languages Lecture 13: Data

    Structures in C Javier Gonzalez-Sanchez javiergs@asu.edu PERALTA 230U Office Hours: By appointment
  2. jgs Data Structures Linked List (malloc and free)

  3. Javier Gonzalez-Sanchez | CSE240 | Spring 2018 | 3 jgs

    Linked List #include <stdlib.h> struct node { int val; struct node * next; }; struct node * head = NULL; head = malloc(sizeof(struct node )); head->val = 1; head->next = malloc(sizeof(struct node )); head->next->val = 2; head->next->next = NULL; struct node * head = NULL; head = malloc(sizeof(struct node)); if (head == NULL) { return 1; } head->val = 1; head->next = NULL; void print_list(struct node * head) { node * current = head; while (current != NULL) { printf("%d\n", current->val); current = current->next; } }
  4. Javier Gonzalez-Sanchez | CSE240 | Spring 2018 | 4 jgs

    Part 1 #include <stdio.h> #include <stdlib.h> struct node { int val; struct node * next; }; int main() { struct node * head = NULL; head = malloc(sizeof(struct node )); head->val = 1; head->next = malloc(sizeof(struct node )); head->next->val = 2; head->next->next = NULL; push (head, 3); push (head, 4); push (head, 5); print_list(head); printf("-----\n"); pop(&head); pop(&head); pop(&head); print_list(head); }
  5. Javier Gonzalez-Sanchez | CSE240 | Spring 2018 | 5 jgs

    Part 2 void push(struct node * head, int val) { struct node * current = head; while (current->next != NULL) { current = current->next; } current->next = malloc(sizeof(struct node )); current->next->val = val; current->next->next = NULL; }
  6. Javier Gonzalez-Sanchez | CSE240 | Spring 2018 | 6 jgs

    Part 3 int pop(struct node ** head) { int retval = -1; struct node * next_node = NULL; if (*head == NULL) { return -1; } next_node = (*head)->next; retval = (*head)->val; free(*head); *head = next_node; return retval; }
  7. Javier Gonzalez-Sanchez | CSE240 | Spring 2018 | 7 jgs

    Part 4 void print_list(struct node * head) { struct node * current = head; while (current != NULL) { printf("%d\n", current->val); current = current->next; } }
  8. jgs CSE 240 Introduction to Programming Languages Javier Gonzalez-Sanchez javiergs@asu.edu

    Spring 2018 Disclaimer. These slides can only be used as study material for the class CSE240 at ASU. They cannot be distributed or used for another purpose.