Topic One:
The function of deleting the middle node of the linked list is realized by the head node of the given list.
Ideas:
Basic solution:
Go through the list and calculate the number of nodes in the list. Then we calculate the position of the middle node, traverse the linked list again, find the previous position of the middle node, and delete the operation.
However, you can do this only once by traversing the same steps:
|
middle node location |
TD valign= "Top" width= ">1"
1 |
2< /td> |
1 |
3 |
|
4 |
2 |
5 |
3 |
6 |
3 |
7 |
8 |
4 |
|
As you can see, the length of the list increases by two nodes, and the position of the middle node moves one bit to the right. So we can set two variables pre and cur,cur to represent the position of the current traverse, the pre represents the position of the first node of the middle node from the head node to the cur. In the process of traversing the list, cur moves the two nodes to the right once, then the pre moves one node to the right once. Of course, the above process should pay attention to determine whether Cur.next and Cur.next.next is empty. When a traversal is complete, cur points to the last node or to the penultimate node, and the pre points to the position of the previous node of the middle node of the entire list.
Public Static class Node {
Public int value;
Public Node Next;
Public Node (int data) {
this. Value = data;
}
}
Public Static Node Removemidnode (node head) {
if NULL null) {
return head;
}
if null) {
return Head.next;
}
Node pre = head;
Node cur = head.next.next;
while NULL null) {
Pre = Pre.next;
cur = cur.next.next;
}
Pre.next = Pre.next.next;
return head;
It is very common to find the middle node of the linked list in the linked list algorithm. Pay attention to flexible applications.
[algorithm] deletes the middle node of the linked list