编写类removeRightmostHalf
的方法LinkedList
成员。不要调用类的任何方法,也不要使用任何辅助数据结构。
如果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循环内部。 任何帮助!
答案 0 :(得分:1)
我建议您使用两个指针slow
和fast
指针。最初两者都将指向链表的开头。
当您看到fast
指针已到达列表末尾时,只需将慢速指针节点标记为列表的末尾,方法是设置next=null
;
重要提示,列表末尾的发现将取决于列表的偶数/奇数大小。因此,设计和测试两种情况。
答案 1 :(得分:0)
这将有效,当你到达列表的一半时,只需切断与其余部分的链接。
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)
}
祝你好运