JZ14 链表中倒数最后k个结点
原题链接
描述
输入一个链表,输出一个链表,该输出链表包含原链表中从倒数第k个结点至尾节点的全部节点。
如果该链表长度小于k,请返回一个长度为 0 的链表。
示例1
输入:{1,2,3,4,5},1
返回值:{5}
##思路
- 遍历链表变量,存在数组中,然后按序创建链表。
- 假设链表长度为n,求k个结点组成的链表,只要返回第(n - k + 1) 个结点后面的不动就好了。
- 双指针,创建两个结点初始化都指向链表头结点,然后让第一个向后移 k 个结点,如果移动过程中指向null,说明该链表长度小于 k 直接返回null。第一个结点指向第k个时,两个新创建的结点再一起向后移动,直到先移动的结点为null,此时返回第二个结点。
解答
解答一
public class Solution {
public static ListNode FindKthToTail (ListNode pHead, int k) {
ArrayList<Integer> arrayList = new ArrayList<>();
ListNode cur = pHead;
ListNode res = new ListNode(-1);
ListNode head = res;
while (cur != null ){
arrayList.add(cur.val);
cur = cur.next;
}
if (k > arrayList.size())
return null;
else {
// s = 5 - 3
int s = arrayList.size() - k;
while (s < arrayList.size()){
res.next = new ListNode(arrayList.get(s));
res = res.next;
s++;
}
}
return head.next;
}
}
解答二
public class Solution {
public static ListNode FindKthToTail (ListNode pHead, int k) {
ListNode cur = pHead; //用于遍历链表统计长度
ListNode res = new ListNode(-1);//用于指向倒数第k个结点
int len = 0;
while (cur != null ){
len++;
cur = cur.next;
}
if (k <= 0 || k> len) return null;
int index = len -k + 1;
while (index-- > 0){
res.next = pHead;
pHead = pHead.next;
}
return res.next;
}
}
解答三
public class Solution {
public static ListNode FindKthToTail(ListNode pHead, int k) {
if (pHead == null)
return null;
ListNode start = pHead, end = pHead;
while (k-- > 0) {
if (start == null )
return null;
start = start.next;
}
while (start!= null){
start = start.next;
end = end.next;
}
return end;
}
}
本文来自博客园,作者:klaus08,转载请注明原文链接:https://www.cnblogs.com/klaus08/p/15104989.html

浙公网安备 33010602011771号