注:此博客不再更新,所有最新文章将发表在个人独立博客limengting.site。分享技术,记录生活,欢迎大家关注
题目描述
输入一个链表,输出该链表中倒数第k个结点。
方法一:
思路:倒第k即正第size - k + 1,遍历链表两次,时间复杂度O(n)
/*
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 (head == null || k <= 0) return null;
int size = 0;
ListNode cur = head;
while (cur != null) {
size ++;
cur = cur.next;
}
if (k > size) return null;
cur = head;
for (int i = 1; i != size - k + 1; i ++) {
cur = cur.next;
}
return cur;
}
}
方法二:
双指针,先让第一个指针和第二个指针都指向头结点,然后再让第一个指针走(k-1)步,到达第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) {
if (head == null || k <= 0) return null;
ListNode cur1 = head;
ListNode cur2 = head;
for (int i = 1; i != k; i ++) {
if (cur1.next != null) {
cur1 = cur1.next;
} else {
return null;
}
}
while (cur1.next != null) {
cur1 = cur1.next;
cur2 = cur2.next;
}
return cur2;
}
}