- 反转链表;固定的while循环
while(head != null){
next = head.next;
head.next = pre;
pre = head;
head = next;
}
- 删除某个固定的节点【需要判断是不是删除头节点】;
Node preHead = new Node(-1);
preHead.next = head;
pre = ...;
if (head.vaule == ...){
pre.next = pre.next.next;
}
public static Node removeValue(Node head, int num){
while (head != null){
if (head.value != num){
break;
}
head = head.next;
}
Node pre = head;
Node cur = head;
while(cur != null){
if (cur.value == num){
pre.next = cur.next;
} else {
pre = cur;
}
cur = cur.next;
}
}
- 判断单链表是否有环
while (slow != fast) {
if (fast == null || fast.next == null) {
return false;
}
slow = slow.next;
fast = fast.next.next;
}
- 找到中间节点;n1 = n1.next; n2 = n2.next.next;走一步走两步的技巧
while (slow != fast) {
if (fast == null || fast.next == null) {
return false;
}
slow = slow.next;
fast = fast.next.next;
}
- 有时候可以使用一个假的头节点,来解决头节点被删除和改变的可能
Node fakeNode = new Node(-1);