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
声明:对于转载分享我是没有意见的,出于对博客园社区和作者的尊重一定要保留原文地址哈。
致读者:坚持写博客不容易,写高质量博客更难,我也在不断的学习和进步,希望和所有同路人一道用技术来改变生活。觉得有点用就点个赞哈。








浙公网安备 33010602011771号