LeetCode - Remove Nth Node From End of List
删除链表中倒数第n个节点,需要考虑的细节:链表为空时,链表只有一个节点时,n=1时。
/** * 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) { if(head == null || (head.next == null && n==1)) return null; if(n == 0) return head; ListNode p = new ListNode(1), q = new ListNode(1); p = head; int count = 0; while(p != null) { p = p.next; count ++; } int cur = count - n; if(cur == 0) { ListNode ln = new ListNode(1); ln = head.next; head.next = null; return ln; } count = 0; p = head; while(p != null) { count ++; if(count == cur) break; p = p.next; } q = p.next; p.next = q.next; q.next = null; return head; } }
作者:Pickle
声明:对于转载分享我是没有意见的,出于对博客园社区和作者的尊重一定要保留原文地址哈。
致读者:坚持写博客不容易,写高质量博客更难,我也在不断的学习和进步,希望和所有同路人一道用技术来改变生活。觉得有点用就点个赞哈。
![](https://images2015.cnblogs.com/blog/735119/201701/735119-20170111112835275-168981902.gif)
![](https://images2015.cnblogs.com/blog/735119/201701/735119-20170111112841431-2047172832.jpg)
![](https://images2015.cnblogs.com/blog/735119/201701/735119-20170111112847494-1544911856.jpg)
![](https://images2015.cnblogs.com/blog/735119/201701/735119-20170111112904385-918783221.jpg)
![](https://images2015.cnblogs.com/blog/735119/201701/735119-20170111120143119-1302805212.jpg)
![](https://images2015.cnblogs.com/blog/735119/201701/735119-20170111112856369-1466718103.jpg)
![](https://images2015.cnblogs.com/blog/735119/201701/735119-20170111112830416-794416355.jpg)
![](https://images2015.cnblogs.com/blog/735119/201701/735119-20170111113919510-1155220901.gif)