the 5th element from the tail
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了the 5th element from the tail相关的知识,希望对你有一定的参考价值。
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的主要内容,如果未能解决你的问题,请参考以下文章
[Vue warn]: Unknown custom element: <Top> - did you register the component correctly?
Word2010 Error:The name in the end tag of the element must match the element type in the start tag.
Word2010 Error:The name in the end tag of the element must match the element type in the start tag.
The markup in the document following the root element must be well-formed.Quartz.xml .......
ValueError: The number of elements in ‘fill‘ does not match the number of bands of the image (3 != 4