Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /**
- * Definition for ListNode.
- * public class ListNode {
- * int val;
- * ListNode next;
- * ListNode(int val) {
- * this.val = val;
- * this.next = null;
- * }
- * }
- */
- public class Solution {
- /*
- * @param head: The first node of linked list.
- * @param n: An integer
- * @return: Nth to last node of a singly linked list.
- */
- public ListNode nthToLast(ListNode head, int n) {
- //set first node to position
- ListNode first = head;
- for (int i = 0; i<n;i++){
- first=first.next;
- }
- //increase first and second simultaneously until first comes to the end
- ListNode second = head;
- while(first!=null){
- first = first.next;
- second = second.next;
- }
- return second;
- }
- }
Add Comment
Please, Sign In to add comment