Remove Nth Node From End of List - Leetcode
2015-10-28 09:41
531 查看
题意:
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.
这道题的难易程度是easy,可是笔者就是笨就是不专心然后没想出来,最后还是看网上的思路。设置两个指针,使得两个指针的距离是n-1,一起往后面移动,后面那个指针移到链表末尾时,前面那个指针就指向要删除的位置。
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.
这道题的难易程度是easy,可是笔者就是笨就是不专心然后没想出来,最后还是看网上的思路。设置两个指针,使得两个指针的距离是n-1,一起往后面移动,后面那个指针移到链表末尾时,前面那个指针就指向要删除的位置。
/** * 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) { ListNode* back=head; ListNode* cur=head; ListNode* before=head; //将back指针往后移动n-1位。 for(int i=1;i<n;i++) back=back->next; //直到back指向最后一位时,cur指向要删除的节点 while(back->next!=NULL) { before=cur; back=back->next; cur=cur->next; } //如果cur指向的就是头结点,则要修改head指向的节点 if(cur==head) head=cur->next; else before->next=cur->next; //最后删除cur指向的节点 delete cur; return head; } };
相关文章推荐
- leetcode 179 Largest Number
- leetcode 24 Swap Nodes in Pairs
- leetcode 2 Add Two Numbers 方法1
- leetcode 2 Add Two Numbers 方法2
- [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 题解
- LeetCode [Day 5] Longest Palindromic Substring 题解