题目:输入一个链表,输出该链表中倒数第k个结点
解析:这里提供两种解法,还有一种用栈的解法
解法1:
①遍历一遍链表,获取链表的长度len;
②用链表长度len减去k,此时变成输出顺数第len-k+1个节点了;
public ListNode FindKthToTail1(ListNode head,int k) {
if (head == null) return null;
int len = 0;
ListNode tmp = head;
//遍历获取链表长度
while(tmp != null){
len++;
tmp = tmp.next;
}
//这是判断k的有效性
if (k>len) return null;
//这里遍历为什么不是len-k+1,因为在len-k=0时,
//循环条件不再继续,此时head已是第len-k+1个节点
int num = len-k;
while((num--)!=0){
head = head.next;
}
return head;
}
解法2:双指针
①定义两个指针p1和p2指向头结点,p1先走到第k个节点;
②此时p1和p2同时移动,直到p1移动到链表的末尾;
③p2此时已经指向了p1;
//第一个指针先走k,第二个指针在走,直到第一个指针走完
public ListNode FindKthToTail3(ListNode head,int k) {
if (head == null) return null;
ListNode first = head, second = head;
//第一个指针先走k步
while((k--)!=0){
//这是判断k的有效性
if (first == null)
return null;
first = first.next;
}
//此时第二个指针和第一个指针一起走,直到第一个指针走完
while(first != null){
first = first.next;
second = second.next;
}
return second;
}
用栈的做法:
//Stack来实现,当链表过长,Stack会栈溢出
public ListNode FindKthToTail2(ListNode head,int k) {
if (head == null) return null;
Stack stack = new Stack();
while(head != null){
stack.push(head);
head = head.next;
}
ListNode tmp = null;
while((k--)!=0 ){
if (stack.empty()){
return null;
}
tmp = (ListNode) stack.pop();
}
return tmp;
}