Recursion: Sublist Code - PowerPoint PPT Presentation

About This Presentation
Title:

Recursion: Sublist Code

Description:

temp.insert(index-1, item); head.setNext(temp.head); Sublist Code #2 ... void insert (int index, Object item) { head = insertRec(head, index, item) ... – PowerPoint PPT presentation

Number of Views:17
Avg rating:3.0/5.0
Slides: 9
Provided by: site139
Category:

less

Transcript and Presenter's Notes

Title: Recursion: Sublist Code


1
Recursion Sublist Code
  • class ListReferenceBased implements ListInterface
  • private Node head
  • void insert (int index, Object item)
  • ...

2
Sublist Code 1
  • void insert (int index, Object item)
  • if (index1)
  • head new Node(item, head)
  • else
  • ListReferenceBased temp
  • new ListReferencedBased(head.getNext())
  • temp.insert(index-1, item)
  • head.setNext(temp.head)

3
Sublist Code 2
  • void insert (int index, Object item)
  • if (index1)
  • head new Node(item, head)
  • else
  • Node temp head
  • head head.getNext()
  • insert(index-1, item)
  • temp.setNext(head)
  • head temp

4
Sublist Code 3
  • void insert (int index, Object item)
  • head insertRec(head, index, item)
  • private Node insertRec(Node head, int index,
    Object item)
  • if (index1)
  • head new Node(item, head)
  • else
  • head.setNext(insertRec(head.getNext(), index-1,
    item))
  • return head

5
Linked Binary Trees
  • public class LinkedBinaryTree implements
    BinaryTreeInterface
  • private TreeNode root null
  • public LinkedBinaryTree (TreeNode ref)
  • root ref
  • public boolean isEmpty()
  • return (root null)
  • ...

6
  • public void attachLeftSubTree (LinkedBinaryTree
    leftTree) throws TreeException
  • if (isEmpty() root.getLeft() ! null)
  • throw new TreeException(Empty tree. Bad.)
  • root.setLeft(leftTree.root)
  • leftTree.makeEmpty()
  • public BinaryTreeInterface detachRightSubtree()
  • throws TreeException
  • if (isEmpty())
  • throw new TreeException(Empty tree. Stop
    it.)
  • BinaryTreeInterface tree new
  • LinkedBinaryTree(root.getRight()
  • root.setRight(null)
  • return tree

7
  • public boolean contains (Object item)
  • if (isEmpty())
  • return false
  • if (root.getItem().equals(item))
  • return true
  • BinaryTreeInterface left detachLeftSubtree()
    BinaryTreeInterface right detachRightSubtree()
  • boolean result left.contains(item)right.conta
    ins(item)
  • attachLeftSubtree(left)
  • attachRightSubtree(right)
  • return result

8
  • public Object findRightMost()
  • if (isEmpty())
  • return null
  • BinaryTreeInterface right detachRightSubtree()
  • Object result null
  • if (right.isEmpty())
  • result getRootItem()
  • else
  • result right.findRightMost()
  • attachRight(right)
  • return result
Write a Comment
User Comments (0)
About PowerShow.com