Presentation is loading. Please wait.

Presentation is loading. Please wait.

COMP104 Linked List Algorithms / Slide 1 Some Simple Algorithms on Linked Lists * Write a function that returns the length of a given list. * Write a boolean.

Similar presentations


Presentation on theme: "COMP104 Linked List Algorithms / Slide 1 Some Simple Algorithms on Linked Lists * Write a function that returns the length of a given list. * Write a boolean."— Presentation transcript:

1 COMP104 Linked List Algorithms / Slide 1 Some Simple Algorithms on Linked Lists * Write a function that returns the length of a given list. * Write a boolean function that tests whether a given unsorted list of characters is a palindrome. * Write a function that computes the union of two sorted linked lists of integers.

2 int length(NodePtr Head) { int size = 0; NodePtr cur = Head; while(cur != NULL){ size++; cur = cur->next; } return size; } The length of a given list:

3 int lengthRec(NodePtr Head) { if(Head==NULL) return 0; return length(Head->next) + 1; } It can also be recursive:

4 COMP104 Linked List Algorithms / Slide 4 bool isPalindrome(NodePtr head) { 1. create a new list in inverse order, newList 2. check the two lists, head and newList, whether they are the same } Test if the given list is a palindrome: [a b c d d c b a] is a palindrome, [a b c d c] is not.

5 bool isPalindrome(NodePtr Head){ bool result; // copy the list in reverse order NodePtr newList = NULL; NodePtr cur = Head; while(cur != NULL){ addHead(newList, cur->data); cur = cur->next; } // compare the list and reversed list result = true;// assume true cur = Head; rev = newList; while(cur!=NULL){ if(cur->data != rev->data) result = false;// not palindrome! cur = cur->next; rev = rev->next; } while(newList != NULL){// delete reversed list cur = newList; newList = newList->next; delete cur; } return result;// all same; must be palindrome! } Test if the given list is a palindrome:

6 merge([1, 2, 4, 5], [3, 4, 5, 6, 7]) gives [1, 2, 3, 4, 5, 6, 7] // returns merged list (changes first list) NodePtr merge(NodePtr Head1, NodePtr Head2){ NodePtr Union, Cur; if(Head1==NULL) return Head2; else if(Head2==NULL) return Head1; Union = Head1; Cur = Head2; while(Cur != NULL){ if(searchNode(Union, Cur->data)==NULL) insertNode(Union, Cur->data); Cur = Cur->next; } return Union; } Union of two sorted lists:


Download ppt "COMP104 Linked List Algorithms / Slide 1 Some Simple Algorithms on Linked Lists * Write a function that returns the length of a given list. * Write a boolean."

Similar presentations


Ads by Google