题目描述
输入一个链表,输出该链表中倒数第k个结点。
解题思路
方法1
遍历两边链表
标记序号即可
方法2
遍历一遍链表
先让fast指针走k-1步,确定两指针所指节点距离为k,让两指针联动跑,当fast指针的下一个节点为null时,那么另一个指针所指节点就是倒数第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)return null;
ListNode cur = head;
int count = 0;
while(cur != null){
count++;
cur = cur.next;
}
if(k > count)return null;
cur = head;
int i = 0;
while(i != count - k){
i++;
cur = cur.next;
}
return cur;
}
//方法二
public void BackNode2(int key){
int k = key;
if(k < 0 ){
System.out.println("输入异常!");
return;
}
this.fast = this.head;
this.slow = this.head;
while (k - 1 != 0){
if(fast.next != null){
fast = fast.next;
k--;
}else {
System.out.println("输入异常!");
return;
}
}
while (fast.next != null){
fast = fast.next;
slow = slow.next;
}
System.out.print("倒数第" + key + "个节点为:");
System.out.println(slow.val);
}
}