[英]How should I implement removal of rightmost half of my custom Linkedlist
Write the method removeRightmostHalf
member of the class LinkedList
.编写类
LinkedList
removeRightmostHalf
方法成员。 Do not call any methods of the class and do not use any auxiliary data structures.不调用类的任何方法,也不使用任何辅助数据结构。
If l
contains A! B! C! D! E
如果
l
包含A! B! C! D! E
A! B! C! D! E
A! B! C! D! E
, then after calling l.removeRightmostHalf()
, l
becomes A! B! C
A! B! C! D! E
,然后在调用l.removeRightmostHalf()
, l
变成了A! B! C
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++) {
}
}
I do not know how I will remove inside for loop.我不知道如何删除 for 循环内部。 Any help!
任何帮助!
I would suggest you to use two pointers, slow
and fast
pointer.我建议你使用两个指针,
slow
指针和fast
指针。 Initially both will be pointing to the start of the linked list.最初两者都将指向链表的开头。
The moment you see that fast
pointer has reached the end of the list, just mark the slow pointer node as end of the list, by setting next=null
;当您看到
fast
指针到达列表末尾时,只需通过设置next=null
将慢速指针节点标记为列表末尾;
Important note that, the discovery of the end of the list will be depend on the even/odd size of the list.重要的是要注意,列表末尾的发现将取决于列表的偶数/奇数大小。 So design and test with both cases.
所以设计和测试这两种情况。
This will work , when you reach the half of the list just cut the link with the rest of it.这将起作用,当您到达列表的一半时,只需切断与其余部分的链接。
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)
}
good luck祝你好运
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.