Given a linked list, remove the nth node from the end of list and return its head.
For example,
Given linked list: 1->2->3->4->5, and n = 2. After 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.
Given n will always be valid.
Try to do this in one pass.
去除某个节点,需要维护改节点前面的节点,因为是单向链表,使用两个指针,其中一个比另一个快n步,这里由给出的n都是合法的,因此不需要特殊考虑,不过在实际中若需要考虑n为不合法的情况,则需要直接返回。
public ListNode removeNthFromEnd(ListNode head, int n) { if(head == null || n == 0) return head; ListNode dummy = new ListNode(0); dummy.next = head; ListNode temp1 = head; while(n > 0) { temp1 = temp1.next; n--; } // since n is valid, there is no need to check here, but should discuss with interviewer. If n is invalid, terminate here ListNode temp = dummy, temp2 = head; while(temp1 != null) { temp1 = temp1.next; temp2 = temp2.next; temp = temp.next; } temp.next = temp2.next; return dummy.next; }
没有评论:
发表评论