Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.*;
- import java.lang.*;
- import java.io.*;
- import java.util.function.*;
- class Node
- {
- public int val;
- public Node next;
- }
- class ListUtils
- {
- public static void print(Node n) {
- System.out.printf("%d", n.val);
- for(Node cur = n.next; cur != null; cur = cur.next) {
- System.out.printf(", %d", cur.val);
- }
- System.out.println();
- }
- public static Node reverse(Node n) {
- if (n == null) return n;
- Node cur = n.next;
- Node prev = n;
- prev.next = null;
- while(cur != null) {
- Node temp = cur.next;
- cur.next = prev;
- prev = cur;
- cur = temp;
- }
- return prev;
- }
- /* interface Function<T, R> {
- * T apply(R arg);
- * }
- */
- public static Node map(Node n, Function<Integer, Integer> mapper) {
- for(Node cur = n; cur != null; cur = cur.next) {
- cur.val = mapper.apply(cur.val);
- }
- return n;
- }
- /* interface Predicate<T> {
- * boolean test(T arg);
- * }
- */
- public static Node filter(Node n, Predicate<Integer> tester) {
- Node root = new Node();
- Node prev = root;
- for(Node cur = n; cur != null; cur = cur.next) {
- if(tester.test(cur.val)) {
- prev.next = cur;
- prev = cur;
- }
- }
- prev.next = null;
- return root.next;
- }
- public static Node filter2(Node n, Predicate<Integer> tester) {
- Node begin = null;
- for(Node cur = n; cur != null; cur = cur.next) {
- if(tester.test(cur.val)) {
- begin = cur;
- break;
- }
- }
- Node prev = begin;
- for(Node cur = begin.next; cur != null; cur = cur.next) {
- if(tester.test(cur.val)) {
- prev.next = cur;
- prev = cur;
- }
- }
- prev.next = null;
- return begin;
- }
- public static void main(String[] args)
- {
- Node n4 = new Node();
- n4.val = 9;
- n4.next = null;
- Node n3 = new Node();
- n3.val = 7;
- n3.next = n4;
- Node n2 = new Node();
- n2.val = 5;
- n2.next = n3;
- Node n1 = new Node();
- n1.val = 3;
- n1.next = n2;
- Node n0 = new Node();
- n0.val = 1;
- n0.next = n1;
- ListUtils.print(n0);
- Node rev = ListUtils.reverse(n0);
- ListUtils.print(rev);
- ListUtils.print(n0);
- Node mapped = ListUtils.map(
- rev,
- i -> i * 3 - 1
- );
- ListUtils.print(mapped);
- Node filtered = ListUtils.filter2(
- mapped,
- i -> i % 4 == 0
- );
- ListUtils.print(filtered);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement