[CrackCode] 2.2 Find the nth to last element of a singly linked list

来源:互联网 发布:js 获取cookie的值 编辑:程序博客网 时间:2024/06/06 20:00

Implement an algorithm to find the nth to last element of a singly linked list.

==========
Analysis:
Similar problem as "Remove Nth Node From End of List" in LeetCode.  Idea is to use two pointers, distance between which is n.  So, when the right pointer reached the end of the link list, the left pointer is pointing to the nth to last element.
public class Answer {public static LinkedListNode solution(LinkedListNode head, int n){if(head == null) return null;LinkedListNode left = head;LinkedListNode right = head;for(int i=0; i<n-1; i++){if(right.next!=null) right = right.next;else return null;}while(right.next!=null){left = left.next;right = right.next;}return left;}public static void main(String[] args) {LinkedListNode head = AssortedMethods.randomLinkedList(10, 0, 10);System.out.println(head.printForward());int nth = 11;LinkedListNode n = solution(head, nth);if (n != null) {System.out.println(nth + "th to last node is " + n.data);} else {System.out.println("null");}}}

Note: Please download crackcode library before running the program. 
  

0 0
原创粉丝点击