NOTE: Please do NOT copy and paste code already supplied for this question. See
ID: 3650686 • Letter: N
Question
NOTE: Please do NOT copy and paste code already supplied for this question. See question below.Write a function called "odd" that takes a linked list and returns the odd-numbered elements. Actually, write two functions called "odd" and "even". odd(L) returns a list of the 1st,3rd,5th... items in L. even(L) returns a list of the 2nd,4th,6th... items in L. And each function calls the other. These two functions are based on a simple observation. L.next is like L, but with the first item missing. If we take away the first item, item N+1 becomes item N. So the 2nd,3rd,4th elements of L are the 1st,2nd,3rd elements of L.next. Now if N+1 is odd, N is even, while if N+1 is even N is odd. So the odd members of L.next are even members of L, and the even members of L.next are odd members of L. Then we can compute odd(L) as follows. If L is null return null. Otherwise return a list whose first item is L.item, while its tail is even(L.next). To compute even(L): If L is null return null. Otherwise return odd(L.next). Your main function should read a list of positive integers from the command line, with -1 terminating the list. It should form a linked list containing these integers, compute the list of odd members, and print them
Sample keyboard input: 3 28 37 8 12 5 9
when odd method is called
1 37 12 9
when even method is called
28 8 5
Thanks but please do not copy and paste code that has been provided for this question. Thanks.
Explanation / Answer
import java.io.*; class linkedlist { int key; linkedlist next; public linkedlist(int k,linkedlist n) { key=k; next=n; } public int getKey() { return key; } public linkedlist getNext() { return next; } public linkedlist odd(linkedlist l) { if(l==null) return null; l.next=even(l.next); return l; } public linkedlist even(linkedlist l) { if(l==null) return null; return odd(l.next); } } public class test { public static void main(String[] args) { linkedlist list1,list2; //creates two linked list having integers 1,2,3,4,5,6 list1=new linkedlist(1,new linkedlist(2,new linkedlist(3,new linkedlist(4,new linkedlist(5,new linkedlist(6,null)))))); list2=new linkedlist(1,new linkedlist(2,new linkedlist(3,new linkedlist(4,new linkedlist(5,new linkedlist(6,null)))))); //odd elements of linked list linkedlist temp=list1.odd(list1); System.out.println(" Odd position elements are:"); while(temp!=null) { System.out.println(temp.key); temp=temp.next; } //even elements of linked list temp=list2.even(list2); System.out.println(" Even position elements are:"); while(temp!=null) { System.out.println(temp.key); temp=temp.next; } } }
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.