链表中间

d3v*_*pro 0 c++

当我们没有被告知其大小时,如何找到链表的中间,并且必须仅使用一个循环和仅一个指针来执行.

Pau*_*ury 13

怎么样

LinkedList * llist = getLList(); // the linked list
Node * node = llist.head;

while ( node ) {
    node = node.next;
    if ( node ) {
        node  = node.next;
        llist.remove( llist.head );
    }
}
// now llist.head is (er, um... was) the middle node.  
// hope you didn't need the rest of the list.
Run Code Online (Sandbox Code Playgroud)

  • @SadSido:显然,如果我有一个链表,我有一堆指针,包括头部.我认为这个问题意味着一个指针,除了那些已经在列表中的指针. (3认同)
  • 哈哈!太棒了! (2认同)
  • @SadSido:是的,我确实意识到我正在摧毁这个过程中的清单.但是,由于要求非常不自然,我认为解决方案不需要具有额外的弹性. (2认同)

Jon*_*ehl 8

Node *m,*e,*head; /* head is given */
m=e=head;
while(e) {
  e=e->next;
  if (e) {
    e=e->next;
    m=m->next;
  }
}
/* now m is the middle node */
Run Code Online (Sandbox Code Playgroud)

对不起,我不得不用2个指针:)


将此添加到您的答案中,因为小调整会将指针数量减少到1.我希望您不要介意:

Node m,*e,*head; /* head is given */
e = head;
if (e) m = *e;
while(e) {
  e = e->next;
  if (e) {
    e = e->next;
    m = *(m.next);
  }
}
/* now m is the middle node */
Run Code Online (Sandbox Code Playgroud)

  • 好吧,当你作弊时,它根本没有挑战性. (3认同)