一 循环定位的问题
1 从头到尾遍历链表的方法
- 无头结点
while
循环体内,
第一次循环,count为1,head指向第2个节点;
第二次循环,count为2,head指向第3个节点;
第三次循环,count为3,head指向第4个节点;
…
第length-1次循环,count为length-1,head执行第length个节点;
第length次循环,count为length,head指向length+1为节点(为null);
while循环判断此时的head为null,所以不在进入循环体内
此时count的值即为length
int count = 0;
while (head != null) {
count++;
head = head.next;
}
2 获取指定节点的值
public static void getValue(ListNode head, int location) {
ListNode tail = new ListNode();
tail.next = head;
ListNode current = tail;
for (int i = 0; i < location; i++){
current = current.next;
}
System.out.println("使用头结点\n" + "第" + location + "个节点的值为:" + current.val);
ListNode currentTwo = head;
for (int i = 0; i < location - 1; i++) {
currentTwo = currentTwo.next;
}
System.out.println("不使用头结点\n" + "第" + location + "个节点的值为:" + currentTwo.val);
int n = 0;
while (n < location) {
n++;
}
}