How to remove the first node of a linked list and add to a new linked list in java? I know removing and adding but, I'm confused how to transfer the data element from one node to the other.
1 Answer
This sounds like a school assignment, so I won't give you the actual code, but here is an overview of what you need to implement:
- Let's name your two linked lists
AandB(I'm going to assume you're dealing with singly linked lists). You want to remove the first node ofAand add it to the end ofB - First, you need to find the tail (last) node of
B. It should have a field callednextor something of that sort. - Make
B.tail.nextpoint to the location thatA.headreferences (the first node of A) - Make
A.headpoint to the location thatA.head.nextreferences (aka the second node of A) - Set
B.tail.nextto NULL (keep in mind thatB.tailhas now been updated to point to the old first node ofA).
That's it! Make sure you do these in the right order, or you may overwrite a pointer that you need.