【问题标题】:Java: method of a methodJava:方法的方法
【发布时间】:2017-05-19 23:40:04
【问题描述】:

我有以下代码,它是一个双向链表。暂时忽略 cmets。 (我从 github 上的某个地方复制了重要部分,所以如果你发现类似的东西不要感到惊讶)。

我的问题非常基本,我需要以下表达式:

n.n.next 的 n.previous。

如果我没记错的话,n.next 和 n.previous 都是方法。

我该怎么做?

提前致谢

public class DoublyLinkedList {

int size =0;
Knoten head = null;
Knoten tail = null;


public Knoten addAtEnd(int data){
    Knoten n = new Knoten(data);
    if(size==0){
        head = n;
        tail = n;
    }else{
        tail.next = n;
        n.previous = tail;
        tail =n;
    }
    size++;
    return n;
}

public Knoten Search(int data)
{
    Knoten n = new Knoten(data);
    /*for i in DoublyLinkedList
    /*if hat n.data = data(of parameter)
     * {n.next of previous n n is now : n.next
     * n.previous of next n = n previous
     * }
     */
    size--;
    return n;
}

public Knoten delete(int data)
{
    Knoten n = new Knoten(data);
    if(n.previous != null)
    {

    /*  n.next of n.previous = n.next
     * n.previous of n.previous = n previous
     */
    }
    else {
        // n.next is now head
    }

    size--;
    return n;
}



public static void main(String[] args) {
    DoublyLinkedList d = new DoublyLinkedList();
    d.addAtEnd(3);
}

}

class Knoten
{
    int data;
    Knoten next;
    Knoten previous;

    public Knoten(int data)
    {
        this.data = data;
        next = null;
        previous = null;  
    }
}

【问题讨论】:

  • 它们不是方法...
  • 所以你想要n.previous.next
  • 说,我有一个 1 , 4 , 6 n = 4 n.previous.next 的列表,对吗?所以 n.previous.next = n.next 应该是 6 对吧?
  • 否 @A.Y n.previous().next() == n -- n==4,将一个(上一个)返回到 1,然后再将一个(下一个)前移到 4。
  • @A.Y 你为什么不试试呢?

标签: java list methods


【解决方案1】:

那个类Knoten实现了一个doubly linked list pattern,所以nextprevious是指向链表中开始和结束节点的指针,需要遍历链表。链表可以在这里描述:

ThisDoublyLinkedList 是Java 中的一个简单实现。 你可以在这里看到next()previous() 是如何作为方法实现的:

        public Item next() {
            if (!hasNext()) throw new NoSuchElementException();
            lastAccessed = current;
            Item item = current.item;
            current = current.next; 
            index++;
            return item;
        }

        public Item previous() {
            if (!hasPrevious()) throw new NoSuchElementException();
            current = current.prev;
            index--;
            lastAccessed = current;
            return current.item;
        }

但这不是他们在Knoten 类中的行为方式。

【讨论】:

    猜你喜欢
    • 2018-09-27
    • 1970-01-01
    • 2020-04-30
    • 2020-01-30
    • 1970-01-01
    • 2011-02-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多