0

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:

  1. 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.

  2. How do I swap the position of nodes for lets say node 1 and node 2?

  3. How do I sort the LinkedList based on the name in ascending order (assuming the name is 'albumName')?

4

2 回答 2

2

1.)您必须编写某种find(int)返回 Node 的方法,该方法将允许您获取对要删除的节点的引用。

假设你有一个双链接的,你可以改变周围节点的引用,垃圾收集器会清理那个节点的内存。

如果它是符号链接的,则需要使用 for 循环来找到要删除的节点,然后使用对当前节点之后的上一个节点的引用,将 prev 中的 next 的引用更改为 curr.next .

2.) 如果你写了一个 find 方法,你可以切换节点中的数据,或者你可以在你的 remove 中使用类似的 for 循环来改变节点的引用。

3.) 使用将对数据进行排序的节点编写选择排序。节点不一定需要移动,您可能只需切换数据。

for(Node curr = this.head; curr != null; curr = curr.next)
    for(Node next = curr.next; next != null; next = next.next)

类似的东西。

于 2013-01-01T01:09:24.050 回答
0

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:

于 2013-01-01T00:54:01.920 回答