题目
LeetCode 19. Remove Nth Node From End of List
思路
思路一:
- 单链表, 无法从尾结点往前遍历. 那么可以将倒数第N个结点转为第
L-N+1个正数节点
- 长度L可以提前遍历一次来求值
- 移除第
L - N + 1个节点
思路二:
- 利用双指针
- 先让两个指针相隔
N - 1的位置
- 然后双指针同步后移
- 当第二个指针到了尾部, 第一个指针恰好在倒数第N个节点的前驱位置.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58
|
class Solution { public ListNode removeNthFromEnd(ListNode head, int n) { return removeByTwoPointer(head, n); } private ListNode removeByTwoPointer(ListNode head, int n) { ListNode support = new ListNode(0); support.next = head; ListNode first = support; ListNode second = support; int i = 0; while (i < n) { second = second.next; i++; } while (second != null && second.next != null) { second = second.next; first = first.next; } first.next = first.next.next; return support.next; } private ListNode removeByTwoPass(ListNode head, int n) { ListNode support = new ListNode(0); support.next = head; int length = 1; ListNode iter = head; while(iter.next != null) { iter = iter.next; length++; } length -= n; iter = support; while(length > 0) { length--; iter = iter.next; } iter.next = iter.next.next; return support.next; } }
|