剑指Offer----链表中倒数第k个节点

来源:互联网 发布:北京节能环保中心 知乎 编辑:程序博客网 时间:2024/06/06 16:28

输入一个链表,输出该链表中倒数第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||k<=0)return null;        ListNode pAhead=head;        ListNode pBhead=null;        for(int i=0;i<k-1;i++){            if(pAhead.next!=null)pAhead=pAhead.next;             else return null;        }        pBhead=head;        while(pAhead.next!=null){            pBhead=pBhead.next;            pAhead=pAhead.next;        }        return pBhead;    }}
方法二:
public class Solution {    public ListNode FindKthToTail(ListNode head,int k) {      if (head == null)   return null;        ListNode node = head;        int count = 0;        while (node != null) {            count++;            node = node.next;        }        if (count < k)  return null;        ListNode p = head;        for (int i = 0; i < count - k; i++) {            p = p.next;        }        return p;    }}