1 / 8

Linking pointers

Linking pointers. Typdef struct _link{ int value; struct _link *next; } link; link l1, l2, l3, l4; link *p1, *p2, *p3, *p4; p1 = &l1; p2 = &l2; p3 = &l3; p4 = &l4; l1.value = 1; l2.value = 2; l3.value = 4; l4.value = 8;. p1->next = p2; p2->next = p3; p3->next = p4;

sharla
Download Presentation

Linking pointers

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. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Linking pointers Typdefstruct _link{ int value; struct _link *next; } link; link l1, l2, l3, l4; link *p1, *p2, *p3, *p4; p1 = &l1; p2 = &l2; p3 = &l3; p4 = &l4; l1.value = 1; l2.value = 2; l3.value = 4; l4.value = 8; p1->next = p2; p2->next = p3; p3->next = p4; p4->next = p1; p1->value = 5; p1->next->value = 3; p1->next->next->value = 7; for(i=0;i<4;i++) { printf(“%d, “,p2->value); p2 = p2->next; } p2 = null; p3 = null; p4 = null;

  2. Linked Lists • How to operate on an existing linked list • How to modify (or create) a linked list

  3. Linked List • The simplest linked list contains only one variable – the head, which points to the first node in the linked list • That node may, in turn, point to another • which may point to another node • and so on • The last node’s next point is NULL

  4. Struct for a linked list typedefstruct _node{ int value; struct _node *next; } node; typedefstruct _linkedlist{ node *head; } linkedlist;

  5. Function that sums the items in the list intsumlinkedlist(linkedlist *list) { node *tmp; int sum = 0; // the loop when you want to do something to every // node in a linked list for(tmp = head; tmp != NULL;tmp = tmp->next) sum += tmp->value; //array[i]; return sum; }

  6. Arrays vs Linked Lists • Arrays are good if you want to write once and read many times • Linked Lists are good if you want to make many modifications (additions and deletions)

  7. Creating a linked list from scratch linkedlist *createAndInitializeLinkedList() { linkedlist list; list.head = NULL; return &list; } linkedlist *createAndInitializeLinkedList() { linkedlist *list = (linkedlist *)malloc(sizeof(linkedlist)); list->head = NULL; return list; }

  8. // remove the first item from list and return its value intremoveFromHead(linkedlist *list) { node *n; int v; if (list->head == NULL) return -1; // remove node from list n = list->head; list->head = list->head->next; // free node v = n->value; free (n); // return node’s value field return v; }

More Related