Leetcode_19:Remove Nth Node From End of List
2017-07-26 21:46
369 查看
Question:
Given a linked list, remove the nth node from the end of list and return its head.
给定一个链表,从列表末端删除n个节点并返回它的头部。
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一直有效,尝试着一次通过。
Answer:
Given a linked list, remove the nth node from the end of list and return its head.
给定一个链表,从列表末端删除n个节点并返回它的头部。
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一直有效,尝试着一次通过。
Answer:
public class Solution { public ListNode removeNthFromEnd(ListNode head, int n) { //没有待删除的结点 if (n==0) return head; ListNode countHead = head; int listNum = getListNum(countHead); //删除所有结点 if (listNum==1) return null; else{ if(n==listNum){ head=head.next; return head; } int count = 1; ListNode startHead = head; ListNode preHead = null; while(count<listNum-n+1){ if(count==listNum-n){ preHead = startHead;//待删除结点的前一个结点 } startHead=startHead.next; count++; } //System.out.println(count); preHead.next=startHead.next; return head; } } public int getListNum(ListNode head){ int nodeNum = 0; while(head.next!=null){ nodeNum++; head=head.next; } nodeNum++; return nodeNum; } } class ListNode{ int val; ListNode next; ListNode(int x){val=x;} }
相关文章推荐
- LeetCode 19. Remove Nth Node From End of List
- LeetCode-19-Remove Nth Node From End of List(C语言实现)
- [leetcode]19. Remove Nth Node From End of List
- LeetCode 19. Remove Nth Node From End of List(删除单链表倒数第N个结点)
- python实现 LeetCode19——Remove Nth Node From End of List
- [C语言][LeetCode][19]Remove Nth Node From End of List
- [LeetCode - 双指针] 19. Remove Nth Node From End of List
- [LeetCode 19] Remove Nth Node From End of List Solutions
- [LeetCode]#19 Remove Nth Node From the End of list
- 【LeetCode】19. Remove Nth Node From End of List (2 solutions)
- leetcode_[python/C++]_19. Remove Nth Node From End of List(删除链表末第n个节点)
- LeetCode | #19 Remove Nth Node From End of List
- leetcode--19. Remove Nth Node From End of List
- LeetCode问题解答:19. Remove Nth Node From End of List
- Leetcode 19. Remove Nth Node From End of List
- leetcode 19. Remove Nth Node From End of List
- leetcode 19. Remove Nth Node From End of List
- LeetCode(19) Remove Nth Node From End of List
- Java [leetcode 19]Remove Nth Node From End of List
- leetcode 19. Remove Nth Node From End of List