LeetCode OJ刷题历程——Remove Nth Node From End of List
来源:互联网 发布:pl sql developer下载 编辑:程序博客网 时间:2024/06/03 20:55
Given a linked list, remove the nth node from the end of list and return its head.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.
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 *p,*q,*r;int count = 0;r = p = q = head;while(p->next){p = p->next;if(count>=n-1)q = q->next;if(count>=n)r = r->next;count++;}if(count == 0) head = NULL;else if(r == q) head = head->next;r->next = q->next;q->next = NULL;return head; }};这里只使用了一次遍历,p指针开始遍历,q指针相对于p延迟n-1个时间开始遍历,用以得到倒数第n个结点位置,而r指针用以得到倒数第n+1个结点位置,用以删除操作。
这个题目同样需要注意特殊情况,如链表只有一个结点的情况,应该返回NULL
Given nums = [2, 7, 11, 15], target = 9,Because nums[0] + nums[1] = 2 + 7 = 9,return [0,1].
0 0
- LeetCode OJ刷题历程——Remove Nth Node From End of List
- LeetCode OJ:Remove Nth Node From End of List
- LeetCode OJ - Remove Nth Node From End of List
- [LeetCode OJ]Remove Nth Node From End of List
- LeetCode OJ Remove Nth Node From End of List
- 【LeetCode OJ 019】Remove Nth Node From End of List
- leetcode oj java Remove Nth Node From End of List
- <LeetCode OJ> 19. Remove Nth Node From End of List
- [LeetCode OJ] 19. Remove Nth Node From End of List
- LeetCode OJ - Remove Nth Node From End of List
- Leetcode OJ -Remove Nth Node From End of List
- LeetCode OJ-19.Remove Nth Node From End of List
- LeetCode——Remove Nth Node From End of List
- Remove Nth Node From End of List —— Leetcode
- leetcode—Remove Nth Node From End of List
- leetcode刷题日记——Remove Nth Node From End of List
- 【LeetCode】LeetCode——第19题:Remove Nth Node From End of List
- LeetCode 第十九题 Remove Nth Node From End of List
- CodeForces 106C Buns (01beoba)
- Java的反射机制详解
- Android开发问题汇总–持续更新
- Threading Performance 2
- linux学习笔记
- LeetCode OJ刷题历程——Remove Nth Node From End of List
- C++扬帆远航——1
- 【C#】面向对象基础—属性、方法、结构
- TP整合微信遇到的一系列问题
- unity学习阶段笔记
- leetcode:Spiral Matrix II 【Java】
- Xcode里一个工程(Project)多个项目(target)做版本控制讨论
- 1.跨浏览器通讯之iframe 以及window.open
- 华为oj 将真分数分解为埃及分数