标签:nod link end example move etc tco fast color
描述
Given a linked list, remove the n
th node from the end of list and return its head.
For example, Given linked list: 1->2->3->4->5, and n = 2.
Aer removing the second node from the end, the linked list becomes 1->2->3->5.
Note:
? Given n will always be valid.
? Try to do this in one pass.
分析
代码
1 public static ListNode removeNthNodeFromEnd(ListNode head, int n) { 2 if (head == null || n == 0) 3 return head; 4 ListNode fast = head, slow = head, p = head; 5 int len = 1; 6 while (p.next != null) { 7 p = p.next; 8 len++; 9 } 10 if (n == len) { 11 return head.next; 12 } 13 n = n % len; 14 for (int i = 0; i < len - n - 1; i++) { 15 fast = fast.next; // fast会比i多进1 16 } 17 slow = fast.next; 18 fast.next = slow.next; 19 return head; 20 }
Remove Nth Node From End of List LeetCode Java
标签:nod link end example move etc tco fast color
原文地址:https://www.cnblogs.com/ncznx/p/9160875.html