输入一个链表,输出该链表中倒数第k个结点。

来源:互联网 发布:linux local命令 编辑:程序博客网 时间:2024/06/10 23:02
/*
public class ListNode {
    int val;
    ListNode next = null;


    ListNode(int val) {
        this.val = val;
    }
}*/
public class Solution {
    public ListNode FindKthToTail(ListNode head,int k) {
        ListNode node_k=null;
        ListNode node=head;
        int total=0;
        while(head !=null){
            //统计链表中一共有多少个节点
            total++;
            head=head.next;
        }
        head=node;
      if(total - k >=0){
          for(int i=1;i<=total-k;i++){
              //遍历查找倒数第k个节点
              head=head.next;
          }
          node_k=head;
      }
        return node_k;
    }
}
阅读全文
0 0
原创粉丝点击