链表中倒数第 k 个节点
(倒数从 1 开始计数)
第一种方法:
需要遍历链表两次:第一次统计出链表中节点的个数,第二次找到倒数第 k 个节点
/*function ListNode(x){ this.val = x; this.next = null; }*/ function FindKthToTail(head, k) { // write code here let p = head; let number = 0; while(p!=null){ p = p.next; number++; } if(number-k+1<=number&&number-k+1>0){ for(let i=0;i<number-k;i++){ head = head.next; } return head; }else{ return; } }
第二种方法:
只需要遍历链表一次,利用两个指针
/*function ListNode(x){ this.val = x; this.next = null; }*/ function FindKthToTail(head, k) { // write code here let pAhead = head; if(head==null||k<=0){ return; } for(let i=0;i<k-1;i++){ if(pAhead.next!=null){ pAhead = pAhead.next; }else{ return null; } } let pAfter = head; while(pAhead.next!=null){ pAhead = pAhead.next; pAfter = pAfter.next; } return pAfter; }
有三种可能让代码崩溃的情况:
- 输入的 head 为空指针
- k=0 时,倒数第 0 个数是不存在的
- pAhead 的节点数小于 k,由于会在链表上先向前走 k-1 步,若节点数小于 k 说明倒数的数不存在