[英]How should I implement removal of rightmost half of my custom Linkedlist
編寫類LinkedList
removeRightmostHalf
方法成員。 不調用類的任何方法,也不使用任何輔助數據結構。
如果l
包含A! B! C! D! E
A! B! C! D! E
A! B! C! D! E
,然后在調用l.removeRightmostHalf()
, l
變成了A! B! C
A! B! C
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 循環內部。 任何幫助!
我建議你使用兩個指針, slow
指針和fast
指針。 最初兩者都將指向鏈表的開頭。
當您看到fast
指針到達列表末尾時,只需通過設置next=null
將慢速指針節點標記為列表末尾;
重要的是要注意,列表末尾的發現將取決於列表的偶數/奇數大小。 所以設計和測試這兩種情況。
這將起作用,當您到達列表的一半時,只需切斷與其余部分的鏈接。
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)
}
祝你好運
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.