LeetCode 019 Remove Nth Node From End of List
2014-03-29 10:57
459 查看
题目
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个给删除。
思路
1 条件中,n永远合法,所以减少了错误判断所需的内容。
2 第一次last,先记录 离head n的节点在哪。
3 第二次,保留一个pre , pre 和 last同时前进,这样,当last指向最后一个节点的时候,pre正好是所要删除的节点的前一个节点。
4 进行删除操作。
代码
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.
链表中倒数第n个给删除。
思路
1 条件中,n永远合法,所以减少了错误判断所需的内容。
2 第一次last,先记录 离head n的节点在哪。
3 第二次,保留一个pre , pre 和 last同时前进,这样,当last指向最后一个节点的时候,pre正好是所要删除的节点的前一个节点。
4 进行删除操作。
代码
public class Solution { public ListNode removeNthFromEnd(ListNode head, int n) { if(head==null){ return null; } ListNode dummy = new ListNode(Integer.MIN_VALUE); dummy.next = head; ListNode last =dummy; for(int i=0;i<n;i++){ last = last.next; } ListNode pre = dummy; while(last.next!=null){ last=last.next; pre=pre.next; } pre.next = pre.next.next; return dummy.next; } }
相关文章推荐
- Palindrome Number
- Max Points on a Line
- Evaluate Reverse Polish Notation
- Sort List
- Insertion Sort List
- LRU Cache
- Binary Tree Postorder Traversal
- Binary Tree Preorder Traversal
- Reorder List
- Linked List Cycle
- Linked List Cycle II
- Word Break
- Word Break II
- Copy List with Random Pointer
- Single Number
- Single Number II
- Candy
- Gas Station
- Clone Graph
- Palindrome Partitioning