Guest User

Untitled

a guest
May 23rd, 2018
80
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.81 KB | None | 0 0
  1. /**
  2. * Definition for ListNode.
  3. * public class ListNode {
  4. * int val;
  5. * ListNode next;
  6. * ListNode(int val) {
  7. * this.val = val;
  8. * this.next = null;
  9. * }
  10. * }
  11. */
  12.  
  13.  
  14. public class Solution {
  15. /*
  16. * @param head: The first node of linked list.
  17. * @param n: An integer
  18. * @return: Nth to last node of a singly linked list.
  19. */
  20. public ListNode nthToLast(ListNode head, int n) {
  21. //set first node to position
  22. ListNode first = head;
  23. for (int i = 0; i<n;i++){
  24. first=first.next;
  25. }
  26.  
  27. //increase first and second simultaneously until first comes to the end
  28. ListNode second = head;
  29. while(first!=null){
  30. first = first.next;
  31. second = second.next;
  32. }
  33. return second;
  34. }
  35. }
Add Comment
Please, Sign In to add comment