LeetCoder_____Remove Nth Node From End of List(11)
来源:互联网 发布:linux 删除命令 编辑:程序博客网 时间:2024/06/14 03:30
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.
题意:
给出一个链表,删除倒数第n个节点。
分析:
两个指针p1,p2,一个指针p1先走n步,然后同时一起走,当p1为NULL,删除p2所处节点即可。
在面试中出现这种题目需要注意一些地方:(程序的鲁棒性)
1.给出的head指针为NULL。
2.给出的n为非正数。
3.给出的n超过链表的长度。
4.当删除的节点为头节点或者尾节点。
代码:
class Solution {public: ListNode* removeNthFromEnd(ListNode* head, int n) { if(head == NULL || n == 1 && head->next == NULL) return NULL; if(n <= 0)return head; ListNode* p1,*p2; p1 = p2 = head; if(n == 1){ while(p1->next->next != NULL) p1 = p1->next; p1->next = NULL; return head; } for(int i = 0 ; i < n ; i ++){ if(p1 == NULL) return head->next; p1 = p1->next; } while(p1 != NULL){ p1 = p1->next; p2 = p2->next; } p2->val = p2->next->val; p2->next = p2->next->next; return head; }};
0 0
- LeetCoder_____Remove Nth Node From End of List(11)
- Remove Nth Node From End of List
- Remove Nth Node From End of List
- Remove Nth Node From End of List
- Remove Nth Node From End of List
- Remove Nth Node from End of List
- Remove Nth Node From End of List
- Remove Nth Node From End of List
- Remove Nth Node From End of List
- Remove Nth Node From End of List
- Remove Nth Node From End of List
- Remove Nth Node From End of List
- Remove Nth Node From End of List
- Remove Nth Node From End of List
- Remove Nth Node From End of List
- Remove Nth Node From End of List
- Remove Nth Node From End of List
- Remove Nth Node From End of List
- 【高中数学】三棱锥体积公式
- Centos7 安装 PHP7最新版
- 表单提交eMail
- 跟随鼠标一起流动的粒子动画 JS 原生代码
- 项目后期Lua接入笔记01--框架及IDE
- LeetCoder_____Remove Nth Node From End of List(11)
- Spring学习(一):Spring是什么
- 有线无线同时使用
- 如何将两个表名对调
- 关于org.apache.struts2.dispatcher.filter.StrutsPrepareAndExecuteFilter找不到的问题
- 使用xml配置方式开发SpringMVC
- fastjson特性之解析出子类属性
- vue.js 解决空格报错!!!
- Mycat高级进阶---事务支持