leetcode:Remove Nth Node From End of List
来源:互联网 发布:国外电脑网络加速器 编辑:程序博客网 时间:2024/06/06 14:12
题目
给定一个列表,删除倒数第n个节点,并且返回表头,例如:
给定列表:1->2->3->4->5, n = 2
返回:1->2->3->5
假设给定的n值都是合法的。
注意
- 给定空表,返回NULL
- 如果删除第一个节点,要保证不要删了表头
思路
设置两个指针p,q,相差
struct ListNode { int val; ListNode *next; ListNode(int x) : val(x), next(NULL) {} };class Solution {public: ListNode* removeNthFromEnd(ListNode* head, int n) { if (NULL == head) {return head;} ListNode *p = head; ListNode *q = head; ListNode *pPre = NULL;//记录 p 指针直接前驱 for(int i = 0;i != n - 1;++i) q = q->next; while(q->next) { pPre = p; q = q->next; p = p->next; } if(NULL == pPre)//要删除的节点是第一个节点 { head = p->next; delete p; } else { pPre->next = p->next; delete p; } return head; }};
0 0
- LeetCode[Linked List]: Remove Nth Node From End of List
- 19. Remove Nth Node From End of List leetcode list
- [Leetcode]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
- [Leetcode] Remove Nth Node From End of List
- LeetCode: Remove Nth Node From End of List
- leetcode 40: 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
- LeetCode-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
- leetcode之Remove Nth Node From End of List
- 自定义的布局文件
- hdu2795Billboard【线段树】
- 数据库的事务处理
- Oracle-常用监控SQL
- IL中间语言理解学习001-Add加法解析
- leetcode:Remove Nth Node From End of List
- Remove advertisement of Storm 5
- POJ 3693 Maximum repetition substring(好题)
- Android Studio导入Project的方法
- centos 7 网络配置( 网关、dns、ip地址配置)
- NYOJ 16 矩形嵌套(DAG上的DP)
- C++: byte和int的相互转化
- Linux下守护进程(daemon)和管道的结合使用(代码保留)
- 重造轮子-random5到random7