最近面试快手,手撕代码的时候发现既不是关键代码模式也不是ACM,而是从数据结构开始写起,有点懵。记录在此,一起学习!
//链表结构体
class ListNode{
int val;
ListNode next=null;
ListNode(int val){
this.val = val;
}
}
public class LastK {
public static void main(String[] args) {
ListNode listNode = new ListNode(0);
ListNode head = listNode;
for (int i = 1; i < 5; i++) {
listNode.next = new ListNode(i);
listNode = listNode.next;
}
//链表:0 1 2 3 4 倒数第二个结点 是3
int res = power(head, 2);
System.out.println(res);
}
static int power(ListNode head,int k){
ListNode first = head;
ListNode second = head;
for (int i = 0; i < k; i++) {
second = second.next;
}
while(second!=null){
first = first.next;
second = second.next;
}
return first.val;
}
}