[英]Deleting the second last node from a LinkedList in java
I'm working on a method that is supposed to delete the node prior to the last one,the logic seems quite fine with me, but when I tried to implement it in a project, it didn't work out. 我正在研究一种应该删除最后一个节点之前的节点的方法,这种逻辑在我看来似乎还不错,但是当我尝试在项目中实现该节点时,效果却不佳。 ( Oh and I'm using MyLinkedList) (哦,我正在使用MyLinkedList)
here's the code: 这是代码:
public void deleteSec(){
Node current = head;
Node p = head.next;
Node q = null;
while(p.next!=null){
q = current;
current.next = p;
p = p.next;
}
q.next = p; // q.next = q.next.next;
}
What if your LL is empty? 如果您的LL为空怎么办? head will be null and this will cause an exception when you call head.next; head将为null,这将在您调用head.next时导致异常。
you have to take care of special cases like: empty LL, LL with one node, LL with two nodes. 您必须处理一些特殊情况,例如:空LL,具有一个节点的LL,具有两个节点的LL。
Here is my code: 这是我的代码:
public void deleteSec() {
if (head == null) {
return;
}
if (head.next == null) {
return;
}
if (head.next.next == null) {
head = head.next;
return;
}
Node current = head;
Node p = current.next;
Node q = p.next;
while (q.next != null) {
current = current.next;
p = p.next;
q = q.next;
}
current.next = q;
}
if(myLinkedList.size() > 1) {
myLinkedList.remove(myLinkedList.size()-2);
}
well i personally compiled it, 好吧,我亲自编写了它,
Assuming the node class is named Node and you have a getNext() method that returns the next Node or null if this Node is the last node, you would do something like this. 假设节点类名为Node,并且您有一个getNext()方法返回下一个Node,或者如果该Node是最后一个节点,则返回null,您将执行以下操作。
if (head == null) // or if (first == null)
{
return; // There are no elements in the list.
}
Node currect = head; // This is the head, or Node current = first;
Node previous = null;
while (current.getNext() != null)
{
previous = current;
currrent = current.getNext();
}
Then do this to make the second to last pointer to next null.
if (previous != null)
{
previous.setNext( null );
}
else
{
// The list has 1 entry only.
head = null; // or first = null;
}
If deleting a second last node would be a common operation, as it is in my case, I would suggest an extra prev
or previous
node added to the Node
construction. 如果删除第二个最后一个节点将是一个常见的操作,因为它是在我的情况,我建议一个额外的prev
或previous
加入节点Node
建设。
Usually a linked list node would be 通常一个链表节点是
private static class Node<Item> {
private Item item;
private Node<Item> next;
}
But I modified it to be like 但我将其修改为
private static class Node<Item> {
private Item item;
private Node<Item> prev;
private Node<Item> next;
}
Thus, if you want to delete the second last, the implementation would be pretty straightforward: 因此,如果要删除倒数第二个,实现将非常简单:
oldSecondLast = last.prev; // Assumes last points to the last node
oldSecondLast.next = last;
last = oldSecondLast.prev;
oldSecondLast = null; // To avoid loitering
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.