题解 | #输出单向链表中倒数第k个结点#

输出单向链表中倒数第k个结点

http://www.nowcoder.com/practice/54404a78aec1435a81150f15f899417d

import java.util.*; public class Main { private class ListNode{ private int key; private ListNode next; private ListNode(){ } public ListNode(int key,ListNode next){ this.key=key; this.next=next; } } private ListNode tail; private ListNode head; private int size=0; public Main(){ tail=null; head=null; } public void add(int num){ if(tail==null){ head = new ListNode(num,null); tail =head; }else{ ListNode Node = head; while(Node.next !=null){ Node = Node.next; } Node.next=new ListNode(num,null); tail=Node.next; } } public int getSize(int size){ this.size=size; return size; } public void clear(){ tail =null; head = null; } public int get(int num){ int key= size-num; ListNode Node = head; for(int i=0;i<key;i++){ Node = Node.next; } if(Node ==null){ return 0; } else{ return Node.key; }

}
  public static void main(String [] args){
      Main m = new Main();
      Scanner sc= new Scanner(System.in);
      while(sc.hasNext()){
      int size =sc.nextInt();
      m.getSize(size);
      
      for(int i=0;i<size;i++){
          m.add(sc.nextInt());
      }   
      System.out.println(m.get(sc.nextInt()));
      m.clear();
  }
  }

}

全部评论

相关推荐

头像
昨天 15:46
已编辑
中南大学 后端
字节国际 电商后端 24k-35k
点赞 评论 收藏
分享
点赞 收藏 评论
分享
牛客网
牛客企业服务