Created
February 13, 2013 02:51
-
-
Save zhoutuo/4932996 to your computer and use it in GitHub Desktop.
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Definition for singly-linked list. | |
* struct ListNode { | |
* int val; | |
* ListNode *next; | |
* ListNode(int x) : val(x), next(NULL) {} | |
* }; | |
*/ | |
class Solution { | |
public: | |
ListNode *removeNthFromEnd(ListNode *head, int n) { | |
// Start typing your C/C++ solution below | |
// DO NOT write int main() function | |
if(head == NULL) { | |
return head; | |
} | |
ListNode tmpHead(-1); | |
tmpHead.next = head; | |
ListNode* cur = &tmpHead; | |
ListNode* forward = cur; | |
while(n--) { | |
forward = forward->next; | |
} | |
while(forward->next != NULL) { | |
forward = forward->next; | |
cur = cur->next; | |
} | |
ListNode* deleted = cur->next; | |
cur->next = deleted->next; | |
return tmpHead.next; | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment