Some Simple Algorithms on Linked Lists - PowerPoint PPT Presentation

About This Presentation
Title:

Some Simple Algorithms on Linked Lists

Description:

Write a function that returns the length of a given list. ... rev = rev- next; while(newList != NULL){ // delete reversed list. cur = newList; ... – PowerPoint PPT presentation

Number of Views:61
Avg rating:3.0/5.0
Slides: 7
Provided by: csU54
Category:

less

Transcript and Presenter's Notes

Title: Some Simple Algorithms on Linked Lists


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
The length of a given list
  • int length(NodePtr Head)
  • int size 0
  • NodePtr cur Head
  • while(cur ! NULL)
  • size
  • cur cur-gtnext
  • return size

3
It can also be recursive
  • int lengthRec(NodePtr Head)
  • if(HeadNULL)
  • return 0
  • return length(Head-gtnext) 1

4
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.
  • 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

5
Test if the given list is a palindrome
  • bool isPalindrome(NodePtr Head)
  • bool result
  • // copy the list in reverse order
  • NodePtr newList NULL
  • NodePtr cur Head
  • while(cur ! NULL)
  • addHead(newList, cur-gtdata)
  • cur cur-gtnext
  • // compare the list and reversed list
  • result true // assume true
  • cur Head
  • rev newList
  • while(cur!NULL)
  • if(cur-gtdata ! rev-gtdata)
  • result false // not palindrome!
  • cur cur-gtnext
  • rev rev-gtnext

6
Union of two sorted lists
  • 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(Head1NULL)
  • return Head2
  • else if(Head2NULL)
  • return Head1
  • Union Head1
  • Cur Head2
  • while(Cur ! NULL)
  • if(searchNode(Union, Cur-gtdata)NULL)
  • insertNode(Union, Cur-gtdata)
  • Cur Cur-gtnext
  • return Union
Write a Comment
User Comments (0)
About PowerShow.com