Remove Nth Node From End of List
2014-04-02 15:27
351 查看
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.
思路:这道题从尾结点开始删除给定索引的值,然后再输出删除后的结点。我们可以使用两个指针pPost,pPre来解这道题,而且还要保存后面指针的前一结点为删除指定结点做准备。想让pPre先走n-1步,然后循环pPre和pPost共同起步行走,每一次之前都要把pPost保存下来,直到pPre->next为空循环结束。然后判断pTemp。
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.
思路:这道题从尾结点开始删除给定索引的值,然后再输出删除后的结点。我们可以使用两个指针pPost,pPre来解这道题,而且还要保存后面指针的前一结点为删除指定结点做准备。想让pPre先走n-1步,然后循环pPre和pPost共同起步行走,每一次之前都要把pPost保存下来,直到pPre->next为空循环结束。然后判断pTemp。
/** * 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) { if(head==NULL) return NULL; ListNode *pTemp=NULL; ListNode *pPre=head; ListNode *pPost=head; for(int i=0;i<n-1;i++) pPre=pPre->next; while(pPre->next!=NULL) { pTemp=pPost; pPre=pPre->next; pPost=pPost->next; } if(pTemp==NULL) { head=head->next; } else { pTemp->next=pPost->next; } return head; } };
相关文章推荐
- 算法系列——Remove Nth Node From End of List
- leetcode.19----------Remove Nth Node From End of List
- LeetCode 之 Remove Nth Node From End of List — C++ 实现
- Remove Nth Node From End of List
- LeetCode 之 Remove Nth Node From End of List
- 019 Remove Nth Node From End of List
- LeetCode 19 : Remove Nth Node From End of List (Java)
- LeetCode: Remove Nth Node From End of List
- LeetCode 19.Remove Nth Node From End of List
- Leetcode: Remove Nth Node From End of List
- leetcode 19:Remove Nth Node From End of List(15-10-7)
- 第19题 Remove Nth Node From End of List
- Remove Nth Node From End of List
- Leetcode: Remove Nth Node From End of List
- [leetcode刷题系列]Remove Nth Node From End of List
- 第二周:19. Remove Nth Node From End of List
- LEETCODE: Remove Nth Node From End of List
- 【leetcode】19. Remove Nth Node From End of List
- [leetcode] Remove Nth Node From End of List
- [LeetCode] Remove Nth Node From End of List 移除链表倒数第N个节点