Leetcode 19. Remove Nth Node From End of List
来源:互联网 发布:虐杀原形帧数优化补丁 编辑:程序博客网 时间:2024/05/22 11:57
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个节点。
题目分析:使用双指针相聚n-1,当第二个指针遍历到链表尾部则第一个指针就是要删除的节点指针。这里有个问题,因为要删除节点,所以不添加头结点的话,要把删除第一个节点,和其他节点区分开来(第一个节点没有前驱)。如果添加则可以统一处理。下面分别是两种代码,运行时间都是4ms
方法一(不添加头节点):
/** * 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||head->next==NULL) return NULL; ListNode* first=head; ListNode* second=head; for(int i=0;i<n-1;i++) second=second->next; if(second->next==NULL){//删除第一个节点 head=head->next; return head; } while(second->next->next){ second=second->next; first=first->next; } first->next=first->next->next; return head; }};方法二(添加头节点):
/** * 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 h(INT_MAX); h.next=head; ListNode *pfirst=&h; ListNode *psecond=&h; ListNode *temp;//释放被删除的空间 for(int i=0;i<n;i++) psecond=psecond->next; while(psecond->next){ psecond=psecond->next; pfirst=pfirst->next; } temp=pfirst->next; pfirst->next=pfirst->next->next; delete temp; return h.next; }};
0 0
- 19. Remove Nth Node From End of List leetcode list
- [LeetCode]19.Remove Nth Node From End of List
- LeetCode 19. Remove Nth Node From End of List
- 19. Remove Nth Node From End of List Leetcode Python
- LeetCode --- 19. Remove Nth Node From End of List
- LeetCode 19.Remove Nth Node From End of List
- [Leetcode] 19. Remove Nth Node From End of List
- [leetcode] 19.Remove Nth Node From End of List
- <LeetCode OJ> 19. Remove Nth Node From End of List
- 19. Remove Nth Node From End of List LeetCode
- leetcode 19. Remove Nth Node From End of List
- [LeetCode OJ] 19. Remove Nth Node From End of List
- LeetCode 19. Remove Nth Node From End of List
- Leetcode:19. Remove Nth Node From End of List(JAVA)
- leetcode 19. Remove Nth Node From End of List
- Leetcode 19. Remove Nth Node From End of List
- 【LeetCode】19. Remove Nth Node From End of List
- leetcode 19.Remove Nth Node From End of List
- 第十周项目1(1)
- 求2000以内的素数
- 开发团队的效率
- 操作系统——进程与线程
- 流媒体开发(二)后台音频播放
- Leetcode 19. Remove Nth Node From End of List
- linux复制远程文件和文件夹
- 第9周项目1—深复制体验 (2)
- B - Game of Robots
- 第十周项目1(2)
- Ubuntu日常开发环境搭建软件列表
- 最近笔记
- 验证11gR2 RAC中ASM实例通过gpnp profile获得spfile信息来启动ASM实例
- 链表——复杂链表的复制