码迷,mamicode.com
首页 > 其他好文 > 详细

the 5th element from the tail

时间:2017-12-10 11:15:15      阅读:186      评论:0      收藏:0      [点我收藏+]

标签:front   through   data   ant   number   pointer   less   ==   while   

Write a function that would return the 5th element from the tail (or end) of a singly linked list of integers,
in one pass, and then provide a set of test cases against that function
(please do not use any list manipulation functions that you do not implement yourself).

not one pass:

1)Take 2 pointer move one pointer by 5 position ie, the difference between the two pointer is 5. 
2)Now traverse through the list till the first pointer reaches the end of the list 
3) now the second pointer will be pointing to the 5th element from the last.

One pass:

Another way is using a queue data structure, which size is 5. Then enqueue the value of the linked list, and dequeue the head when the queue is full, after one pass, the head of the queue is the number you want.

Use One pointer to the list and a queue of size 5: 
1) traverse to the 5th node 
2) insert the element at the queue 
3) if the queue is full, take rear element out and insert the new element at the front 
4) repeat it till the pointer reaches null 
5) the rear pointer of the queue contains the 5th element from the tail of the list.

public static Node get5thFromTail(Node head){

    Queue<Node> queue = new LinkedList<Node>();

    while(head != null){

        if(queue.size() == 5){
            queue.poll();
            queue.offer(head);
        } else {
            queue.offer(head);
        }
        head = head.next;
    }

//There are less than 5 node
    if(queue.size() < 5){
        return null;
    }

    return queue.poll();
}

  

the 5th element from the tail

标签:front   through   data   ant   number   pointer   less   ==   while   

原文地址:http://www.cnblogs.com/apanda009/p/8016099.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!