Remove Nth Node From End of List
2017-09-20 16:27
169 查看
原题:
Given a linked list, remove the nth node from the end of list and return its head.
For example,
Note:
Given n will always be valid.
Try to do this in one pass.
即对给定一串链表和整数n,去掉倒数第n个节点。
思考过程:
一开始没多想,直接就写,发现第一个问题是不知道链表长度,只好遍历一下求出长度。然后找到所要去掉的节点之前那个节点listnode1.listnode1.next = listnode1.next.next。当然为了返回这个链表,要在head节点之前加一个节点first,最后返回first.next。最开始没考虑只有一个节点的情况,才意识到要从first开始遍历而不是head,否则只有一个节点的情况没法处理。
结果代码:
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.
Note:
Given n will always be valid.
Try to do this in one pass.
即对给定一串链表和整数n,去掉倒数第n个节点。
思考过程:
一开始没多想,直接就写,发现第一个问题是不知道链表长度,只好遍历一下求出长度。然后找到所要去掉的节点之前那个节点listnode1.listnode1.next = listnode1.next.next。当然为了返回这个链表,要在head节点之前加一个节点first,最后返回first.next。最开始没考虑只有一个节点的情况,才意识到要从first开始遍历而不是head,否则只有一个节点的情况没法处理。
结果代码:
public ListNode removeNthFromEnd(ListNode head, int n) { int length = 0,count = 0; ListNode listNode = head,first = new ListNode(0); first.next = head; while (listNode != null){ listNode = listNode.next; length ++; } listNode = first; while (count < length - n){ listNode = listNode.next; count++; } listNode.next = listNode.next.next; return first.next; }
相关文章推荐
- [leetcode 19] Remove Nth Node From End of List
- 19. Remove Nth Node From End of List
- [LeetCode OJ] 19. 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】19-Remove Nth Node From End of List
- [LeetCode] Remove Nth Node From End of List
- Remove Nth Node From end of List
- LeetCode 19 Remove Nth Node From End of List
- 19. 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刷题记——19. Remove Nth Node From End of List(删除链表倒数第N项)
- Remove Nth Node From End of List
- remove-nth-node-from-end-of-list
- leetcode19-Remove Nth Node From End of List
- 【Leetcode Algorithm】Remove Nth Node From End of List