Leetcode-19. Remove Nth Node From End of List
来源:互联网 发布:python web 框架 编辑:程序博客网 时间:2024/06/15 18:20
题目
删除链表的倒数第n个元素
思路
双指针p1, p2,p1先移动到链表的第n个元素,然后p1和p2一起移动,当p2到达末尾时,p1指向的元素即为要删除的元素的前一个元素。注意处理n大于链表长度的情况。
代码
解法1
class Solution {public: ListNode* removeNthFromEnd(ListNode* head, int n) { if(NULL==head || n<1) return head; ListNode* p = head; while(p) { n--; p = p->next; } if(n == 0) return head->next; if(n < 0) { p = head; while(++n) p = p->next; p->next = p->next->next; } return head; }};
解法2
class Solution {public: ListNode* removeNthFromEnd(ListNode* head, int n) { if(NULL==head || n<1) return head; ListNode *h = new ListNode(0); h->next = head; ListNode* p1 = h, *p2 = h; for(int i=0; i<n && p1; i++, p1 = p1->next); if(NULL == p1) return head; while(p1->next) { p1 = p1->next; p2 = p2->next; } p2->next = p2->next->next; 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
- 写一个简单的JAVA程序
- 2017,不改初心
- 1126. Eulerian Path (25)
- 提高51单片机代码效率
- html的table跨行跨列合并
- Leetcode-19. Remove Nth Node From End of List
- jsp--javabeans
- [BZOJ3118]Orz the MST(单纯形)
- 欢迎使用CSDN-markdown编辑器
- 矩阵基本变换
- C++ STL 学习笔记 map multimap
- mysql相关问题
- C++学习记录5--如何使用math.h中定义的PI
- 漫谈计算机基础之信息的处理与表示(1)