LC——返回倒数第k个节点
题目链接:https://leetcode-cn.com/problems/kth-node-from-end-of-list-lcci/
实现一种算法,找出单向链表中倒数第 k 个节点。返回该节点的值。
示例:
输入: 1->2->3->4->5 和 k = 2
输出: 4
思路:
遍历链表,将值放入集合里,获取倒数第k位的值(集合长度-k=倒数k位的下标)
代码:
public static int kthToLast(ListNode head, int k) {
ArrayList<Integer> collection = new ArrayList<>();
((ArrayList<Integer>) collection).add(head.val);
while (head.next != null){
head = head.next;
((ArrayList<Integer>) collection).add(head.val);
}
return ((ArrayList<Integer>) collection).get(collection.size() - k);
}
主方法:
public static void main(String[] args){
ListNode listNode = new ListNode(1,new ListNode(2,new ListNode(3,new ListNode(4,new ListNode(5)))));
System.out.println("---------="+kthToLast(listNode,2));
}
ListNode类代码:
public class ListNode {
public int val;
public ListNode next;
public ListNode() {
}
public ListNode(int val) {
this.val = val;
}
public ListNode(int val, ListNode next) {
this.val = val;
this.next = next;
}
public int getVal() {
return val;
}
public void setVal(int val) {
this.val = val;
}
public ListNode getNext() {
return next;
}
public void setNext(ListNode next) {
this.next = next;
}
@Override
public String toString() {
return "ListNode{" +
"val=" + val +
", next=" + next +
'}';
}
}
附:
这种方式可能不太好,因为引入了集合,应该引入第二个链表来实现,有兴趣的可以自己试下。