80 likes | 163 Views
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;
E N D
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;
Linked Lists • How to operate on an existing linked list • How to modify (or create) a linked list
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
Struct for a linked list typedefstruct _node{ int value; struct _node *next; } node; typedefstruct _linkedlist{ node *head; } linkedlist;
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; }
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)
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; }
// 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; }