[leetcode] 19. Remove Nth Node From End of List
2016-04-18 20:34
453 查看
Given a linked list, remove the nth node from the end of list and return its head.
For example,
Note:
Given n will always be valid.
Try to do this in one pass.
这道题是删除链表倒数第N个节点,题目难度为Easy。
题目的关键是如何找倒数第N个节点,有经验的同学可能很容易想到用双指针法,让fast指针先走N个节点,然后同时移动快慢指针,当fast指针到达链表尾部时slow指针指向的节点即是倒数第N个节点。另外需要注意的是,如果倒数第N个节点是头节点需要特殊处理,具体代码:class Solution {
public:
ListNode* removeNthFromEnd(ListNode* head, int n) {
ListNode* fast = head;
ListNode* slow = head;
ListNode* prev = NULL;
int cnt = 0;
while(fast && cnt<n) {
fast = fast->next;
cnt++;
}
while(fast) {
fast = fast->next;
prev = slow;
slow = slow->next;
}
if(prev) {
prev->next = slow->next;
return head;
}
else {
return slow->next;
}
}
};
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.
这道题是删除链表倒数第N个节点,题目难度为Easy。
题目的关键是如何找倒数第N个节点,有经验的同学可能很容易想到用双指针法,让fast指针先走N个节点,然后同时移动快慢指针,当fast指针到达链表尾部时slow指针指向的节点即是倒数第N个节点。另外需要注意的是,如果倒数第N个节点是头节点需要特殊处理,具体代码:class Solution {
public:
ListNode* removeNthFromEnd(ListNode* head, int n) {
ListNode* fast = head;
ListNode* slow = head;
ListNode* prev = NULL;
int cnt = 0;
while(fast && cnt<n) {
fast = fast->next;
cnt++;
}
while(fast) {
fast = fast->next;
prev = slow;
slow = slow->next;
}
if(prev) {
prev->next = slow->next;
return head;
}
else {
return slow->next;
}
}
};
相关文章推荐
- leetcode 179 Largest Number
- leetcode 24 Swap Nodes in Pairs
- leetcode 2 Add Two Numbers 方法1
- leetcode 2 Add Two Numbers 方法2
- leetcode----Longest Substring Without Repeating Characters
- [LeetCode]47 Permutations II
- [LeetCode]65 Valid Number
- [LeetCode]123 Best Time to Buy and Sell Stock III
- [LeetCode] String Reorder Distance Apart
- [LeetCode] Sliding Window Maximum
- [LeetCode] Find the k-th Smallest Element in the Union of Two Sorted Arrays
- [LeetCode] Determine If Two Rectangles Overlap
- [LeetCode] A Distance Maximizing Problem
- leetcode_linearList
- leetcode_linearList02
- 021-Merge Two Sorted Lists(合并两个排好序的单链表);leetcode
- LeetCode[Day 1] Two Sum 题解
- LeetCode[Day 2] Median of Two Sorted Arrays 题解
- LeetCode[Day 3] Longest Substring Without... 题解
- LeetCode [Day 4] Add Two Numbers 题解