Guest User

Untitled

a guest
May 26th, 2018
77
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.23 KB | None | 0 0
  1. /**
  2. * Definition for ListNode
  3. * public class ListNode {
  4. * int val;
  5. * ListNode next;
  6. * ListNode(int x) {
  7. * val = x;
  8. * next = null;
  9. * }
  10. * }
  11. */
  12.  
  13. public class Solution {
  14. /**
  15. * @param head: The first node of linked list.
  16. * @param n: An integer
  17. * @return: The head of linked list.
  18. */
  19. public ListNode removeNthFromEnd(ListNode head, int n) {
  20. //move the first pointer to nth position
  21. ListNode first = head;
  22. while(n>0){
  23. n--;
  24. first = first.next;
  25. }
  26.  
  27. //special case: when the n is the legnth of the list: delete the first node straight away
  28. if(first==null) return head.next;
  29. /* can also add a dummy head before head:
  30. ListNode result = new ListNode(0);
  31. result.next = head;
  32. ...
  33. //at the end:
  34. return result.next;
  35. */
  36.  
  37. //if not, move first and second together to find the nth last node and remove
  38. ListNode second = head;
  39. ListNode prev = result;
  40. while(first!=null){
  41. prev = second;
  42. first=first.next;
  43. second=second.next;
  44. }
  45. prev.next = second.next;
  46. return result.next;
  47. }
  48. }
Add Comment
Please, Sign In to add comment