Given a linked list, remove the n-th node from the end of list and return its head.
Example:
1 2 3
| 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.
Follow up:
Could you do this in one pass?
给定一个链表,删除链表的倒数第 n 个节点,并且返回链表的头结点。
示例:
1 2 3
| 给定一个链表: 1->2->3->4->5, 和 n = 2.
当删除了倒数第二个节点后,链表变为 1->2->3->5.
|
说明:
给定的 n 保证是有效的。
进阶:
你能尝试使用一趟扫描实现吗?
想法
快慢指针,快指针指向第K个节点,慢指针指向开始节点,当快指针到达末尾时慢指针正好指向倒数第K的节点。由于要删除该节点,还得记录慢指针的上一个节点。Corner Case:传入参数为空、删除的是头节点、K大于链表长度。
解
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
|
class Solution { public: ListNode *removeNthFromEnd(ListNode *head, int n) { if (head == NULL) { return head; } ListNode *cur = head, *ans = head, *last = NULL; int i = n - 1; while (cur->next != NULL) { if (i <= 0) { last = ans; ans = ans->next; } else { i--; } cur = cur->next; } if (last == NULL) { ListNode *temp = head; head = head->next; delete (temp); } else { last->next = ans->next; delete (ans); } return head; } };
|