View Full Version : Java lists
shadylookin
11-09-2006, 07:58 PM
I have 2 lists linkedlist and linkedlist2. I want to be able to take out the first Card out of linkedlist (which starts at 0) and add it to linkedlist2. then once that is done i want to remove Card 0 from linkedlist. and i want to be able to do this for as many times as i assign to the integer n.
public Deck split(int n) {
//implement
LinkedList<Card> linkedlist= new LinkedList<Card>();
LinkedList<Card> linkedlist2= new LinkedList<Card>();
int i = n;
while (i > 0){
linkedlist2.add(linklist<0>);
linkedlist.remove(0);
i--;}
however the part that i bolded doesn't work so how do i do it?
Roelf
11-09-2006, 08:46 PM
shouldnt the line be:
linkedlist2.add(linkedlist.get(i));
linkedlist.remove(i);
shouldnt the line be:
linkedlist2.add(linkedlist.get(i));
linkedlist.remove(i);
I'm not sure on the implementation of a linkedlist in java but I'm not sure this will achieve what he's after. the variable i will be some number between n and 0. Thus, if we remove(i) we'll not be removing the first card (index 0), but whatever card is at the index equal to i (which will range from n,..., 3,2,1).
Based on looking at his code, I'm guessing the error is a syntax error. In which case, I'd try changing the line
linkedlist2.add(linklist<0>);
TO
linkedlist2.add(linklist.get(0));
OR
linkedlist2.add(linklist.getFirst());
Aradon
11-09-2006, 10:44 PM
Gox is right:
public Deck split(int n) {
//implement
LinkedList<Card> linkedlist= new LinkedList<Card>();
LinkedList<Card> linkedlist2= new LinkedList<Card>();
int i = n;
while (i > 0){
linkedlist2.add(linkedlist.get(0));
linkedlist.remove(0);
i--;
}
You could also change it to
linkedlist2.add(linkedlist.poll());
There are a whole bunch of different ways to do it so I suggest looking at the API:
LinkedList (http://java.sun.com/j2se/1.5.0/docs/api/java/util/LinkedList.html)
vBulletin® v3.8.2, Copyright ©2000-2012, Jelsoft Enterprises Ltd.