0

偶数のノードのケースを処理するように関数を変更しましたが、そのため、私のコードは奇数のノードでは機能しません。なにが問題ですか?

public LinkedList findMiddleNode() {
    Node t1 = this.getHeadNode();
    Node t2 = this.getHeadNode();
    LinkedList l = new LinkedList();
    boolean even = false;
    while(t1.getNext() != null) {
        t1 = t1.getNext();
        if(t1.getNext()!= null && t1.getNext().getNext() != null) {
            t1 = t1.getNext();
            t2 = t2.getNext();              
        }
    }
    if(t1.getNext()!=null) 
        l.insertFirst(t2.getElement());
    else {
        l.insertFirst(t2.getElement());
        l.insertLast(t2.getNext().getElement());
    }
    return l;
}
4

2 に答える 2

1

@oldrinb:あなたの助けを借りて、これが私の更新されたコードです:

public LinkedList findMiddleNode() {
    Node t1 = this.getHeadNode();
    Node t2 = this.getHeadNode();
    LinkedList l = new LinkedList();
    boolean even = false;
    while(t1.getNext() != null && t1.getNext().getNext() != null) {
            t1 = t1.getNext().getNext();
            t2 = t2.getNext();              
    }
    if(t1.getNext()==null) 
        l.insertFirst(t2.getElement());
    else {
        l.insertFirst(t2.getElement());
        l.insertLast(t2.getNext().getElement());
    }
    return l;
}
于 2012-09-12T09:24:46.473 に答える
0
/* determine length of list */
int n = 0;
for (Node cur = getHeadNode(); cur != null; cur = cur.getNext()) {
  ++n;
}

/* go half-way */
int m = n / 2;
Node mid = getHeadNode();
while (m > 0) {
  mid = mid.getNext();
  --m;
}

/* if n is odd, both mid and mid.getNext() are the middle */
if ((n % 2) != 0) {
  Node mid2 = mid.getNext();
  ...
} else {
  ...
}

...または、代わりに、

Node tortoise = getHeadNode();
Node hare = getHeadNode();

do {
  tortoise = tortoise.getNext();
} while (hare.getNext() != null && (hare = hare.getNext().getNext()) != null);

/* tortoise is the middle */
于 2012-09-12T05:39:47.797 に答える