JZ14 链表中倒数第k个结点
题目描述
输入一个链表,输出该链表中倒数第k个结点。
/*
public class ListNode {
int val;
ListNode next = null;
ListNode(int val) {
this.val = val;
}
}*/
public class Solution {
public ListNode FindKthToTail(ListNode head,int k) {
ListNode tempNode = head;
int count = 0;
int i = 0;
while (tempNode != null){
count++;
tempNode = tempNode.next;
}
if (k > count) {
return null;
}
i = count - k;
for (int j = 0; j < i; j++) {
head = head.next;
}
return head;
}
}

/*
public class ListNode {
int val;
ListNode next = null;
ListNode(int val) {
this.val = val;
}
}*/
public class Solution {
public ListNode FindKthToTail(ListNode head,int k) {
if (k <= 0 || head == null) {
return null;
}
ListNode fast = head;
ListNode slow = head;
while (k > 0){
if (fast == null) {
return null;
}
fast = fast.next;
k--;
}
while (fast != null){
fast = fast.next;
slow = slow.next;
}
return slow;
}
}


浙公网安备 33010602011771号