• Post Reply Bookmark Topic Watch Topic
  • New Topic

Doubly Linked Lists  RSS feed

 
Lewis Hanlon
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi, I have a programming class question that I'm really struggling with. It's supposed to be an easy question at the beginning of the assignment, but if you don't have an answer to it it's impossible to do any of the rest of the assignment.

I have been given this code:

class IntList {
IntCell first;
IntCell last;

IntList(IntCell f, IntCell l) {
first = f;
last = l;
}
}

class IntCell {
int contents;
IntCell predecessor;
IntCell successor;

IntCell (int i) {
contents = i;
predecessor = null;
successor = null;
}

IntCell (int i, IntCell p, IntCell s) {
contents = i;
predecessor = p;
successor = s;
}
}

The question is "How would you create the list [7,5,2,9] using this class?"

I can see roughly how the code they have given us works, but i can't figure out how to get more than two elements (first, last) in the list. Can anyone help?

Thanks.
 
Campbell Ritchie
Marshal
Posts: 56593
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You will need methods to add nodes. What you do with a linked list is to replace the "next" node with a real node. If you are at the end of the list, the next will be null, so that's easy. If you are in the middle, you will have to transfer "next" to "next.next."

Try with a singly linked list where you only have "next" references and no "previous" references first.

And welcome to the Ranch.
 
fred rosenberger
lowercase baba
Bartender
Posts: 12565
49
Chrome Java Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
are you supposed to do nothing but USE this class, or are you supposed to MODIFY it?

with a casual glance, i don't think you can do it by only using what's given. it's a good start, but it's missing some important things, i think.
 
Tim LeMaster
Ranch Hand
Posts: 226
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Well I don't see an access modifier on the predecessor and successor. so I think you can do it:



should work just fine in the same package. Ugly and adding/removing elements should be made much more convenient.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!