Reputation: 41
I am currently doing a programming project myself and I require some help.
This is the LinkedList class I am using:
class LinkedList {
Node cursor;
private Node head; // first node in the linked list
private int count;
public int getCount() {
return count;
}
public Node getHead() {
return head;
}
public LinkedList() {
head = null; // creates an empty linked list
count = 0;
}
public void addFront(int n) {
Node newNode = new Node(n);
newNode.setLink(head);
head = newNode;
count++;
}
public void deleteFront() {
if (count > 0) {
Node temp = head;
head = temp.getLink();
temp = null;
count--;
}
}
}
Below are my questions:
How do I create a method to remove a node in the LinkedList at any position? Assuming that the first node has the position of 1, second node has the position of 2 and so on and so forth.
How do I swap the position of nodes for lets say node 1 and node 2?
How do I sort the LinkedList based on the name in ascending order (assuming the name is 'albumName')?
Upvotes: 0
Views: 1481
Reputation: 63
1.) You have to write some sort of find(int)
method that returns a Node that will allow you to get a reference to the node you're looking to remove.
Assuming you have a doubly-linked one, you can just change the references of the nodes around and the garbage collector will clean that node out of memory.
If it's signly-linked, you need to use a for loop that will find the node you want to remove, then, using a reference to the previous node that follows the current one, change the reference of next in prev to be curr.next.
2.) If you write a find method, you can either switch the data in the nodes, or you can use similar for loops from your remove to change the references of the nodes around.
3.) Write a selection sort using nodes that will sort the data. Nodes don't need to necessarily be moved around, you could probably just switch the data.
for(Node curr = this.head; curr != null; curr = curr.next)
for(Node next = curr.next; next != null; next = next.next)
Something like that.
Upvotes: 2
Reputation: 121599
I assume you're using the standard Java "Linked List" collection, and not implementing your own.
If so, all you have to do is look at the Javadoc and/or any number of fine tutorials on Java collections.
For example:
Upvotes: 0