Some Simple Algorithms on Linked Lists - PowerPoint PPT Presentation

1 / 5
About This Presentation
Title:

Some Simple Algorithms on Linked Lists

Description:

cur = cur- next; newList = newList- next; return true; // all same; must be palindrome! ... { NodePtr Union, Cur; if(Head1==NULL) return Head2; else if(Head2 ... – PowerPoint PPT presentation

Number of Views:57
Avg rating:3.0/5.0
Slides: 6
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
  • bool isPalindrome(NodePtr Head)
  • // 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
  • cur Head
  • while(cur!NULL)
  • if(cur-gtdata ! newList-gtdata)
  • return false // not palindrome!
  • cur cur-gtnext
  • newList newList-gtnext
  • return true // all same must be palindrome!

5
Union of two sorted lists
  • // 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