How to find nth element from the end of a singly linked list?

后端 未结 28 1109
感动是毒
感动是毒 2020-12-04 06:08

The following function is trying to find the nth to last element of a singly linked list.

For example:

If the elements are

28条回答
  •  情歌与酒
    2020-12-04 06:33

    In java i will use-

    public class LL {
      Node head;
      int linksCount;
    
       LL(){
         head = new Node();
         linksCount = 0;
       }
    
      //TRAVERSE TO INDEX
      public Node getNodeAt(int index){
        Node temp= head;
        if(index > linksCount){
            System.out.println("index out of bound !");
            return null;
        }
        for(int i=0;i

提交回复
热议问题