HJ51 输出单向链表中倒数第k个结点
牛客网大佬思路:采用头插法实现,这样可以得出结论,倒数第k个 === 整数第k个
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
while (in.hasNext()) {
int length = in.nextInt();
ListNode head = new ListNode(-1);
for (int i = 0; i < length; i++) {
int value = in.nextInt();
ListNode node = new ListNode(value);
node.next = head.next;
head.next = node;
}
int num = in.nextInt();
while (num > 0) {
head = head.next;
num--;
}
System.out.println(head.value);
}
}
}
class ListNode {
Integer value;
ListNode next;
public ListNode(Integer value) {
this.value = value;
this.next = null;
}
}
正常思路:
尾插法,即每次新结点在链表的结尾插入,采用双指针法,快指针与慢指针相差k-1个,当快指针到达链表尾部时,慢指针所指即为倒数第k个节点
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
while (in.hasNext()) {
int length = in.nextInt();
ListNode head = new ListNode(-1);
ListNode tmp = head;
for (int i = 0; i < length; i++) {
int value = in.nextInt();
ListNode node = new ListNode(value);
tmp.next = node;
tmp = tmp.next;
}
int num = in.nextInt();
ListNode fast = head.next;
ListNode slow = head.next;
while (num > 1) {
fast = fast.next;
num--;
}
while (fast.next != null) {
fast = fast.next;
slow = slow.next;
}
System.out.println(slow.value);
}
}
}
class ListNode {
Integer value;
ListNode next;
public ListNode(Integer value) {
this.value = value;
this.next = null;
}
}
HJ55 挑7
如果对7取余为0,结果++,否则观察是否包含7
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int num = in.nextInt();
int res = 0;
for (int i = 7; i <= num; i++) {
if (i % 7 == 0) {
res++;
} else if (String.valueOf(i).contains("7")) {
res++;
}
}
System.out.println(res);
}
}