Topic:
Two functions are implemented, one can delete the second-to-last K-node in a single-linked list, and the other can delete the reciprocal K-node in a doubly-linked list.
Requirements:
If the list length is n, the time complexity reaches O (n), and the additional space complexity reaches O (1).
Answer:
Let the list from the beginning to the tail, each move one step, let the K value minus one, when the list goes to the end, if the K value is greater than 0, the explanation does not need to adjust the linked list, because the list does not have the penultimate K node, the original linked list is returned directly, if the K value equals 0, the list This returns the Head.next directly, which is equivalent to deleting the head node. When the value of K is less than zero, start again from the beginning, and each move one step, let the value of K plus 1. When k equals 0 o'clock, the movement stops, and the node to which it moves is the previous node of the node to be deleted.
The list length is n and to delete the last K nodes, the first node of the reciprocal K-node is the first n-k. After the first traversal, the value of K becomes k-n. On the second traversal, the value of K continues to increase by 1. Add to 0 to stop the traversal, where the position of the N-k node is.
Program:
Single Linked list:
Public Static class Node {
Public int value;
Public Node Next;
Public Node (int data) {
this. Value = data;
}
}
Public Static int lastkth) {
if Null | | Lastkth < 1) {
return head;
}
Node cur = head;
while null) {
lastkth--;
cur = cur.next;
}
if (lastkth = = 0) {
head = Head.next;
}
if (Lastkth < 0) {
cur = head;
while (++lastkth! = 0) {
cur = cur.next;
}
Cur.next = Cur.next.next;
}
return head;
}
Double Linked list:
Public Static class Doublenode {
Public int value;
Public Doublenode last;
Public Doublenode Next;
Public Doublenode (int data) {
this. Value = data;
}
}
Public Static int lastkth) {
if Null | | Lastkth < 1) {
return head;
}
Doublenode cur = head;
while null) {
lastkth--;
cur = cur.next;
}
if (lastkth = = 0) {
head = Head.next;
null;
}
if (Lastkth < 0) {
cur = head;
while (++lastkth! = 0) {
cur = cur.next;
}
Doublenode newnext = Cur.next.next;
Cur.next = Newnext;
if null) {
Newnext.last = cur;
}
}
return head;
}
[algorithm] Deletes the reciprocal k nodes in a single linked list and a doubly linked list.