leetcode做题总结,题目Remove Nth Node From End of List 2012/01/27
2014-11-29 09:31
411 查看
删除链表倒数第N的节点,也没什么难度,用两个指针相隔N个节点,然后同时向后移动,一个到末尾另一个就是第N个节点。
Update 2015/08/28: 上面的题目一上来直接创建三个节点我就呵呵了。。也不知道当时是怎么想的。下面来个正常的吧
/** * 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; } }
相关文章推荐
- [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 && 【九度】题目1517:链表中倒数第k个结点
- LeetCode Online Judge 题目C# 练习 - 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]Remove Nth Node From End of List
- leetcode 40: Remove Nth Node From End of List
- [Leetcode 19] 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] 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