链表中倒数第k个节点
题目描述
| 输入一个链表,输出该链表中倒数第k个结点。 |
思路1
*定义两个指针:第一个指针从链表的头指针开始遍历向前走k-1步,第二个指针保持不动;从第k步开始,第二个指针也开始从链表的头指针开始遍历;由于两个指针的距离保持在k-1,当第一个指针到达链表的尾结点时,第二个指针正好指向倒数第k个节点。
程序(java)
/**
* code1
* 时间复杂度:O(n)
* 空间复杂度:
*/
public class Solution {
public ListNode FindKthToTail(ListNode head, int k) {
if (head == null || k < 1) {
return null;
}
ListNode pAhead = head;
ListNode pBehind = head;
while (k-- > 1) {
if (pAhead.next == null) {
return null;
}
pAhead = pAhead.next;
}
while (pAhead.next != null) {
pAhead = pAhead.next;
pBehind = pBehind.next;
}
return pBehind;
}
}
/*
public class ListNode {
int val;
ListNode next = null;
ListNode(int val) {
this.val = val;
}
}*/
思路2
- 先遍历链表获取链表长度length,然后从头结点开始往后走length-k+1步
程序(java)
/**
* code2
* 时间复杂度:O(n)
* 空间复杂度:
*/
public class Solution {
public ListNode FindKthToTail(ListNode head,int k) {
if (head == null || k < 1) {
return null;
}
int length = 0;
// 计算总的节点数量
ListNode temp = head;
while(temp != null){
length++;
temp = temp.next;
}
if(length < k){
//throw new RuntimeException("k的值超过了链表长度");
return null;
}
// 倒数第k个为正数第totalNum-k+1个
ListNode resultNode = head;
for(int i=1; i<=length-k; i++){
resultNode = resultNode.next;
}
return resultNode;
}
}