1A, 开心~
注意, 题目有进阶要求, 只允许扫链表 1 次,
很多链表题跟这个思路一样, 在遍历链表的时候, 维护一个距离与当前头指针为 (n+1) 的尾巴标记 P 即可, 当扫到链表结尾的时候, 此时 P 正好指向待删除节点的前一个节点
注意几个细节处理:
0: 注意 P 的初始化
1:n > 链表长度时, 无需处理
2:n == 链表长度时, P 此时仍没有指向任何一个节点, 需要特判把头节点删除
- class Solution {
- public ListNode removeNthFromEnd(ListNode head, int n) {
- ListNode org = head;
- ListNode ans = null;
- int cnt = 0;
- while (head != null) {
- head = head.next;
- cnt++;
- if (cnt> n) {
- if (ans == null) ans = org;
- else {
- ans = ans.next;
- }
- }
- }
- if (ans != null && n> 0) {
- if (n == 1) {
- ans.next = null;
- } else {
- ans.next = ans.next.next;
- }
- }
- if (cnt == n) {
- org = org.next;
- }
- return org;
- }
- }
来源: http://www.bubuko.com/infodetail-2667010.html