定一个链表,删除链表的倒数第 个节点,并且返回链表的头结点。

示例:

给定一个链表: 1->2->3->4->5, 和 n = 2.

当删除了倒数第二个节点后,链表变为 1->2->3->5.

说明:

给定的 n 保证是有效的。

/**
* Definition for singly-linked list.
* public class ListNode {
* public int val;
* public ListNode next;
* public ListNode(int x) { val = x; }
* }
*/
public class Solution {
public ListNode RemoveNthFromEnd(ListNode head, int n) {
ListNode p = head;
int count = ;
while(p!=null){
count++;
p = p.next;
}
p = head;
if(count < n){
return null;
}
if(count == n){
return head.next;
}
for(int i=; i<count-n-; i++){
if(p.next != null){
p = p.next;
}
}
if(p.next != null){
p.next = p.next.next;
}
return head;
}
}
/**
* Definition for singly-linked list.
* public class ListNode {
* public int val;
* public ListNode next;
* public ListNode(int x) { val = x; }
* }
*/
public class Solution {
public ListNode RemoveNthFromEnd(ListNode head, int n) {
ListNode p = head;
List<ListNode> nodes = new List<ListNode>();
while(p != null){
nodes.Add(p);
p = p.next;
}
if(n == nodes.Count){
return head.next;
}
nodes[nodes.Count - n -].next = nodes[nodes.Count - n -].next.next;
return head;
}
}

最新文章

  1. CSS系列目录
  2. fzuoj Problem 2129 子序列个数
  3. 微信小程序开发感受
  4. ArcGIS发布服务时缓存切片设置
  5. 自己用C语言写单片机PIC18 serial bootloader
  6. 【随记】Hello World小记
  7. [转]使用Gradle发布Android开源项目到JCenter
  8. js 模块开发之一(模块开发价值)
  9. 影像工作站的数据库安装错误之Win7系统下pg服务无法启动
  10. 使用js为html元素动态添加class
  11. javascript 之DOM篇
  12. JS的一些常见验证代码
  13. POJ 1330 Nearest Common Ancestors / UVALive 2525 Nearest Common Ancestors (最近公共祖先LCA)
  14. 【USACO】AC自动机
  15. ES6和CommonJS的区别 以及 export和module.exports的区别
  16. Select文字居右显示
  17. vi快速查找
  18. DX9 DirectX 索引缓存(IndexBuffer) 代码
  19. MT【53】对数平均做数列放缩
  20. C# 6 的新特性~

热门文章

  1. UML第二次作业:类在类图中的表示
  2. vsCode打开多个终端
  3. linux文本编辑器vim大全
  4. jquery学习-document.ready和document.onload区别
  5. PTA——出现次数最多的数
  6. Mac上,Apache启动正常,却无法访问localhost和127.0.0.1
  7. 关于python的创立模块和导入
  8. Mysql 8.0 导入txt文件操作(课程实验)
  9. mvc框架模式
  10. jumpserver管理入门