Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public class Application {
- public static void main(String[] args) {
- IntList L = new IntList(5, null);
- L.rest = new IntList(10, null);
- L.rest.rest = new IntList(15, null);
- System.out.println(L.get(2));
- System.out.println(L.getRecursive(2));
- }
- }
- public class IntList {
- public int first;
- public IntList rest;
- public IntList(int f, IntList r) {
- first = f;
- rest = r;
- }
- public int size() {
- if (rest == null) {
- return 1;
- }
- return 1 + this.rest.size();
- }
- public int iterativeSize() {
- IntList p = this;
- int totalSize = 0;
- while (p != null) {
- totalSize += 1;
- p = p.rest;
- }
- return totalSize;
- }
- public int get(int i) {
- IntList p = this;
- int listS = 0;
- if(i==0) {
- return first;
- }
- while (p != null) {
- listS++;
- p=p.rest;
- if(listS==i) {
- return p.first ;
- }
- }
- return 0;
- }
- public int getRecursive(int i ) {
- if(i==0) {
- return first;
- }
- return rest.getRecursive(i-1);
- }
Add Comment
Please, Sign In to add comment