Docsity

Recursive Functions in Linked List Practice for CS162 Students, Study notes of Computer Science

Partial preview of the text

Download Recursive Functions in Linked List Practice for CS162 Students and more Study notes Computer Science in PDF only on Docsity!

1

CS162: Introduction to Computer

Science II

Linked List Practice

2

My Own Linked List Class

public class MyLinkedList { private Node first; private class Node { public Object data; public Node next; }

public MyLinkedList() { first = null; }

public Object addFirst() {

... } ... }

3

1. Print()

Using the MyLinkedList class, write a recursive

print function to print out the elements of the

linked list eg.

MyLinkedList mll = new MyLinkedList();

mll.addFirst("D");

mll.addFirst("C");

mll.addFirst("B");

mll.addFirst("A");

mll.print(); // prints out โ€œAโ€, โ€œBโ€, โ€œCโ€, โ€œDโ€

4

1. Print()

public void printHelper(Node n) { if (n == null ) { return ; } else { String s = (String) n.data; // sloppy System. out .println(s); printHelper(n.next); } }

public void print() { printHelper(first); }

7

3. Remove Alternate

Using the MyLinkedList class, write a recursive

function to remove every 2 nd^ element

MyLinkedList mll = new MyLinkedList();

mll.addFirst("D");

mll.addFirst("C");

mll.addFirst("B");

mll.addFirst("A");

mll.removeAlternate(); // results in a list with โ€œAโ€, โ€œCโ€

8

3. Remove Alternate

first

Node

โ€œAโ€

Node

โ€œBโ€

Node

โ€œCโ€

Node

null

โ€œDโ€

first

Node

โ€œAโ€

Node

null

โ€œCโ€

Before

After

9

3. Remove Alternate

public void removeAlternateHelper(Node n) {

if ( n == null ) { return ; } else { Node next = n.next; if ( next == null ) { return ; } else { n.next = next.next; removeAlternateHelper(next.next); } }

}

public void removeAlternate() {

removeAlternateHelper(first);

}