Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.Random;
- public class Q1 {
- public static void main(String[] args) {
- //calling to method - build and initiaize a Node-List
- int[] values = new int[]{4,3,2,6};
- Node<Integer> l1 = valuesToList(values);
- Node<Integer> l2 = valuesToList(new int[]{10,11,19,1,7,100}); //short way to initialize
- Node<Integer> l3 = null;
- System.out.println("----BEFORE----");
- System.out.print("l1: ");
- print(l1);
- System.out.print("l2: ");
- print(l2);
- Node<Integer> tmp1 = l1;
- Node<Integer> tmp2 = l2;
- int k = 0;
- while(tmp1!=null) {
- k = tmp1.getValue();
- //if k is even
- if(k%2==0) {
- deleteByPosition(tmp2, k);
- }
- //if k is odd
- else {
- Node<Integer> tmp = byPosition(tmp2, k);
- if(tmp!=null) {
- if(l3==null) //1st node in l3-chain
- l3 = new Node<Integer>(tmp.getValue());
- else
- l3.setNext(new Node<Integer>(tmp.getValue()));
- }
- }
- tmp1 = tmp1.getNext();
- }
- System.out.println("-----AFTER----");
- System.out.print("l1: ");
- print(l1);
- System.out.print("l2: ");
- print(l2);
- System.out.print("l3: ");
- print(l3);
- } //end of main
- /*
- * deletes a node in the given position
- * return the altered node-list
- */
- public static Node<Integer> deleteByPosition(Node<Integer> head, int pos){
- Node<Integer> tmp = head;
- Node<Integer> previous = byPosition(head, pos-1);
- Node<Integer> oneAfter = byPosition(head, pos+1);
- if(oneAfter!=null)
- previous.setNext(oneAfter);
- return tmp;
- //return previous.setNext(previous.getNext().getNext());
- }
- /*
- * return the node in the given position in a node-list
- * returns the altered node-list
- */
- public static Node<Integer> byPosition(Node<Integer> head, int pos){
- while(pos>1 && head!=null) {
- pos--;
- head = head.getNext();
- }
- return head;
- }
- /*
- * prints a given node-list
- */
- public static void print(Node<Integer> chain) {
- while(chain!=null) {
- System.out.print(chain.getValue()+"->");
- chain=chain.getNext();
- }
- System.out.print("null"+"\n");
- }
- /*
- * builds a new chain of nodes of random genarted numbers
- * input length
- */
- public static Node<Integer> randomList(int length){
- Random rnd = new Random();
- int val = rnd.nextInt();
- Node<Integer> head = new Node<Integer>(val);
- Node<Integer> tmp = head;
- while(length>0) {
- length--;
- val = rnd.nextInt();
- tmp.setNext(new Node<Integer>(val));
- tmp = tmp.getNext();
- }
- return head;
- }
- //--------Util methods to initialize the question--------------------------//
- /*
- * builds a new chain of nodes
- * input - array of values
- */
- public static Node<Integer> valuesToList(int[] values){
- Node<Integer> head = new Node<Integer>(values[0]);
- Node<Integer> tmp = head;
- for (int i = 1; i < values.length; i++) {
- tmp.setNext(new Node<Integer>(values[i]));
- tmp = tmp.getNext();
- }
- return head;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement