collections - Java Challenge in LinkedList -
question 4: given integer array, convert linked list each node containing 1 sequence.
sample input : [1, 3, 4, 5, 8, 9, 11, 13, 14, 15, 16, 20, 23, 30,31,32] sample linked list : [1] -> [3,4,5] -> [8,9] -> [11] -> [13,14,15,16]->[20]->[23]->[30,31,32]
the question may seems easy it's bit difficult answer.can write code above in java without using collection
or linkedlist
?
below code detecting sequence (which might help).
class sequence { public static string detectsequence(int seq[]) { string result = ""; (int = 0; < seq.length - 1; i++) { if (seq[i + 1] == seq[i] + 1) { result += seq[i] + " "; if (i != seq.length - 2) { if (seq[i + 1] != seq[i + 2] - 1) { result += seq[i + 1]; } } } else { result += " "; } } if (seq[seq.length - 1] == seq[seq.length - 2] + 1) { result += seq[seq.length - 1]; } return result; } } class question1 { public static void main(string[] cla) { int seqarray[] = { 4, 1, 2, 3, 4, 5, 8, 4, 7, 4, 5, 6, 7, 7, 7, 7, 7, 10, 11, 13, 1, 2, 3, 4 }; string res = sequence.detectsequence(seqarray); system.out.println(res); } }
just give start...
public yourlinkedlist splittosequences(int[] array) { yourlinkedlist list = new yourlinkedlist(); if(array.length > 0) { yoursequence sequence = new yoursequence(); int currentnumber; int lastnumber = array[0]; sequence.add(lastnumber); for(int index = 1; index < array.length; index++) { currentnumber = array[index]; if(currentnumber != lastnumber + 1) { // curentnumber breaks sequence list.add(sequence); // save old sequence list sequence = new yoursequence(); // , start new 1 } sequence.add(currentnumber); } list.add(sequence); } return list; }
now go , figure out linked list , sequence classes , printing stuff...
a minimalistic implementation of linked list
public class mylinkedlist<t1> { private mylinkedlistitem<t1> first = null; private mylinkedlistitem<t1> last = null; public mylinkedlist() { } public void add(t1 item) { mylinkedlistitem<t1> newitem = new mylinkedlistitem<t1>(item); if (first == null) { first = newitem; } else { last.setnext(newitem); } last = newitem; } @override public string tostring() { stringbuffer buffer = new stringbuffer(); if(first != null) { mylinkedlistitem<t1> current = first; while(current.hasnext()) { buffer.append(current.tostring()); buffer.append(" -> "); current = current.getnext(); } buffer.append(current.tostring()); } return buffer.tostring(); } private class mylinkedlistitem<t2> { private t2 data; private mylinkedlistitem<t2> next = null; public mylinkedlistitem(t2 data) { this.data = data; } public boolean hasnext() { return next != null; } public mylinkedlistitem<t2> getnext() { return next; } public void setnext(mylinkedlistitem<t2> next) { this.next = next; } @override public string tostring() { return data.tostring(); } } }
Comments
Post a Comment