【问题标题】:How should I implement removal of rightmost half of my custom Linkedlist我应该如何实现删除我的自定义 Linkedlist 的最右半部分
【发布时间】:2015-10-10 12:34:38
【问题描述】:

编写方法removeRightmostHalfLinkedList 的成员。不要调用类的任何方法,也不要使用任何辅助数据结构。

如果l包含A! B! C! D! E,那么在调用l.removeRightmostHalf()之后,l变成A! B! C

int size = 0 ; 
int halfSize = 0;
current = head;
while (current.next != null) {
    ++size;
    current=current.next;
}
++size;

if (size % 2 == 0) {
    halfSize = (size / 2);
    for (int i = halfSize + 1; i < size; i++) {
    }
}

我不知道如何删除内部 for 循环。 任何帮助!

【问题讨论】:

  • 如果有人解决了您的问题,请选择答案,不要留下未回答的问题

标签: java data-structures linked-list singly-linked-list


【解决方案1】:

我建议你使用两个指针,slowfast 指针。最初两者都将指向链表的开头。

  • 慢速指针一次移动一个节点。
  • fast 一次将移动两个节点。

当你看到fast指针已经到达链表末尾时,只需将慢指针节点标记为链表尾,通过设置next=null;

重要的是,列表末尾的发现将取决于列表的偶数/奇数大小。因此,对这两种情况进行设计和测试。

【讨论】:

    【解决方案2】:

    这将起作用,当您到达列表的一半时,只需切断与其余部分的链接。

    public void removeRightMost() {
        int size = 0;
        int halfSize = 0;
        current = head;
    
        while (current!= null) {
            size++;
            current = current.next;
        }
    
        if (size % 2 == 0) {
            halfSize = (size / 2);
    
            int count = 0;
            current = head;
    
    /* if the number of elements is even you need to decrease the halfSize 1 because 
    you want the current to reach the exactly half if you have 4 elements the current
    should stop on the element number 2 then get out of the loop */
    
           while (count < halfSize-1) { 
                current = current.next;
                count++;
            }
            current.next=null;      //here the process of the deletion when you cut the rest of the list ,  now nothing after the current (null)
        }
    
        else {
            halfSize = (size / 2);
    
            int count = 0;
            current = head;
            while (count < halfSize) {
                current = current.next;
                count++;
            }
            current.next=null;
        }
    
        current=head;  // return the current to the first element (head)
    }
    

    祝你好运

    【讨论】:

      猜你喜欢
      • 2020-02-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-11-21
      • 1970-01-01
      • 2021-03-24
      相关资源
      最近更新 更多