leetcode做题总结,题目Remove Nth Node From End of List 2012/01/27
来源:互联网 发布:js复选框全选 编辑:程序博客网 时间:2024/06/07 03:29
删除链表倒数第N的节点,也没什么难度,用两个指针相隔N个节点,然后同时向后移动,一个到末尾另一个就是第N个节点。
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { * val = x; * next = null; * } * } */public class Solution { public ListNode removeNthFromEnd(ListNode head, int n) { ListNode newhead = new ListNode(0); ListNode start = new ListNode(0); ListNode end = new ListNode(0); newhead.next = head; end=newhead; start=newhead; for(int i=0;i<n;i++){ if(end.next!=null){ end=end.next; }else return head; } while(end.next!=null){ end=end.next; newhead=newhead.next; } newhead.next=newhead.next.next; return start.next; }}
Update 2015/08/28: 上面的题目一上来直接创建三个节点我就呵呵了。。也不知道当时是怎么想的。下面来个正常的吧
/** * Definition for ListNode. * public class ListNode { * int val; * ListNode next; * ListNode(int val) { * this.val = val; * this.next = null; * } * } */ public class Solution { /** * @param head: The first node of linked list. * @param n: An integer. * @return: The head of linked list. */ ListNode removeNthFromEnd(ListNode head, int n) { // write your code here if (n <= 0) { return null; } ListNode start = new ListNode(0); start.next = head; ListNode p = start; for (int i = 0; i < n; i++) { if (head == null) { return null; } head = head.next; } while (head != null) { head = head.next; p = p.next; } p.next = p.next.next; return start.next; }}
0 0
- leetcode做题总结,题目Remove Nth Node From End of List 2012/01/27
- 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[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
- 类2
- [objective-C] 08.内存管理2
- 负载均衡技术之4算法
- 由冰激凌事件联想分布式系统
- Centos 6.5 安装 Scrapy 0.22.2成功
- leetcode做题总结,题目Remove Nth Node From End of List 2012/01/27
- 纯虚函数与抽象类
- SDL显示中文(一个函数而已)
- C语言 gets()和scanf()函数的区别
- leetcode做题总结,题目Combinations 2012/04/18
- 请用fontAwesome代替网页icon小图标
- 不要62 2089
- Linux驱动开发二:外部中断分析
- 因添加两个webservice引用时提示:{"无法加载协定为“sms.WebServiceSoap”的终结点配置部分,找到了该协定的多个终结点配置。请按名称指示首选的终结点配置部分。"}