[Java] 找出链表中倒数第k个节点

来源:互联网 发布:雅力数据去年赚多少钱 编辑:程序博客网 时间:2024/06/05 03:50

某公司的专业一面面试题

默默地用Java写:

1.大致的数据结构:

class Node{   Node(int value, Node nnode){      this.value=value;      this.nnode=nnode;   }}
2.找到倒数第k个节点的函数findknode()

public static Node findknode(Node head, int k){  if ((Null==head) || (Null==head.nnode))      return head;  cur=head;  knode=head;  nextnode=Null;  count=0;  while(cur!=Null){     count+=1;     if(count>=k){         nextnode=knode.nnode;         knode=nextnode;      }     nextnode=cur.nnode;     cur=nextnode;  }  return knode;}

实际上就是快慢指针的思想,对于链表实际长度小于k的情况,默认返回头节点head。


欢迎指正~

0 0
原创粉丝点击