Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class IntNode{
- int value;
- IntNode next;
- IntNode(int value, IntNode restOfTheList){
- this.value = value;
- this.next = restOfTheList;
- }
- }
- class Solution {
- IntNode head;
- Solution(IntNode head) {
- this.head = head;
- }
- static Solution fromArray(int[] arr) {
- // create a linked list with IntNodes
- int arrLength = arr.length;
- IntNode front = null;
- for (int i = arrLength - 1; i >= 0; i--) {
- front = new IntNode(arr[i], front);
- }
- return new Solution(front);
- }
- void print() {
- IntNode iterator = head;
- while (iterator!=null) {
- System.out.print(iterator.value + " -> ");
- iterator = iterator.next;
- }
- System.out.println("null");
- }
- Solution drop(int toDrop) {
- IntNode iterator = head;
- while (toDrop > 0 && iterator != null) {
- iterator = iterator.next;
- toDrop--;
- }
- return new Solution(iterator);
- }
- // IntNode reverse(IntNode node){
- // if(node == null)return null;
- // node.next = reverse(node.next);
- // node.next.next = node;
- // }
- Solution take(int toTake) {
- if(toTake == 0){
- return new Solution(null);
- }
- if(head == null)return this;
- IntNode restOfTheList = new Solution(head.next).take(toTake - 1).head;
- return new Solution(new IntNode(head.value, restOfTheList));
- // IntNode iterator = head;
- // IntNode front = null;
- // // 1 2 3 4 5 ( 3 )
- // while (toTake > 0 && iterator != null) {
- // front = new IntNode(iterator.value, front);
- // iterator = iterator.next;
- // toTake--;
- // } // 3 2 1
- // return new Solution(front);
- }
- Solution last(int toTakeLast) {
- // 1 2 3 4 5 6 7 8 null
- // ^ ^
- // 3
- // 1, 3
- //
- IntNode iterator = head;
- while (toDrop > 0 && iterator != null) {
- iterator = iterator.next;
- toDrop--;
- }
- return new Solution(iterator);
- }
- public static void main(String[] args) {
- Solution empty = Solution.fromArray(new int[] {});
- Solution list1 = Solution.fromArray(new int[] { 1, 2, 3 });
- Solution list2 = Solution.fromArray(new int[] { 1, 2, 3, 4, 5 });
- // empty.drop(1).print(); // null
- // list1.drop(4).print(); // null
- // list1.drop(0).print(); // 1 -> 2 -> 3 -> null
- // list2.drop(2).print(); // 3 -> 4 -> 5 -> null
- // empty.take(1).print(); // null
- // list2.take(0).print(); // null
- // list1.take(4).print(); // 1 -> 2 -> 3 -> null
- // list2.take(3).print(); // 1 -> 2 -> 3 -> null
- empty.last(1).print(); // null
- list2.last(0).print(); // null
- list1.last(4).print(); // 1 -> 2 -> 3 -> null
- list2.last(3).print(); // 3 -> 4 -> 5 -> null
- empty.print(); // null
- list1.print(); // 1 -> 2 -> 3 -> null
- list2.print(); // 1 -> 2 -> 3 -> 4 -> 5 -> null
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement