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.
ListNode *removeNthFromEnd(ListNode *head, int n) {if(n <= 0 || !head)return head;// take slow pointer and fast pointerListNode *slow = NULL;ListNode *fast = NULL;// move fast pointer to n nodeswhile(n > 0){if(!fast)fast = head;elsefast = fast->next;if(!fast)break;n--;}if(!fast)return head;fast = fast->next;// now move slow pointer and fast pointerListNode *prevNode = NULL;slow = head;while(fast){if(!prevNode){prevNode = slow;}else {prevNode = prevNode->next;}fast = fast->next;}// now needif(!prevNode)head = head->next;elseprevNode->next = prevNode->next->next;return head;}
No comments:
Post a Comment