Saturday, August 19, 2017

LeetCode - 19. Remove Nth Node From End of List

Source Link:
https://leetcode.com/problems/remove-nth-node-from-end-of-list/description/ 

Question:
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

Hint:
https://leetcode.com/problems/remove-nth-node-from-end-of-list/solution/

My Solution:
Note:
1. we will add an auxiliary "dummy" node, which points to the list head. The "dummy" node is used to simplify some corner cases such as a list with only one node, or removing the head of the list.
2. Remove the (L−n+1)th node from the beginning in the list, where L is the list length. This problem is easy to solve once we found list length L.
3. starts from the "head" to count the length of the list.
ListNode dummy = new ListNode(0);
dummy.next = head;

4. starts from the "dummy", so we can remove the "head" (without extra error)
current = dummy;
5. the node number (that we want to remove)
while(node_number != L-n+1){
current = current.next;
node_number++;
}

6. remove the node
current.next = current.next.next; 
7.
return dummy.next;

No comments:

Post a Comment

Codility - Lesson 16 Greedy algorithms - 2. MaxNonoverlappingSegments

Source Link: https://app.codility.com/programmers/lessons/16-greedy_algorithms/max_nonoverlapping_segments/ Question: Located on a line ...