LeetCode -- Remove Nth Node From End of List
来源:互联网 发布:淘宝快递助手 编辑:程序博客网 时间:2024/05/21 18:50
移除链表的倒出第n个节点。
思路:
本题还是考察链表的删除操作,如果要删除节点h:
如果h不是最后节点,
h.val = h.next.val;
h.next = h.next.next;
如果h为最后节点,
h = null;
第一次遍历找到倒数第n个为正数第几,然后找到删除的点直接删除就可以了。
实现代码:
思路:
本题还是考察链表的删除操作,如果要删除节点h:
如果h不是最后节点,
h.val = h.next.val;
h.next = h.next.next;
如果h为最后节点,
h = null;
第一次遍历找到倒数第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) { if(head == null){ return null; } if(n == 1 && head.next == null){ return null; } var len = 0; var h = head; while(head != null){ head = head.next; len ++; } if(len - n < 0){ return null; } var nth = len - n + 1; var tmp = h; if(nth < len){ var c = 1; while(c < nth){ h = h.next; c ++; } h.val = h.next.val; h.next = h.next.next; }else{ while(h.next.next != null) {h = h.next;} h.next = null; } return tmp; }}
2 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
- IOS9 QQ阿里微信跳转调整
- 稳定排序与不稳定排序
- CROSSWALK入门
- UITableView/UITabBarController/可视化编程/自动布局
- WebSocket实时通讯实践
- LeetCode -- Remove Nth Node From End of List
- maven环境快速搭建(如何在pom.xml导入一个jar包)(导入ojdbc错误的原因)
- 获取类字节码文件 .class 文件的3种方法
- 一年奋斗与惨淡收场
- ==在Integer中和String类中的使用问题
- LeetCode -- Reverse Integer
- Isomorphic Strings 两个字符串的同构 map操作
- LeetCode -- Reverse Linked List
- Gradle小计