LeetCode-探索-初级算法-链表-2.删除链表的倒数第N个节点(个人做题记录,不是习题讲解)
LeetCode探索-初级算法:https://leetcode-cn.com/explore/interview/card/top-interview-questions-easy/
- 删除链表的倒数第N个节点
-
语言:java
-
思路:用list记录遍历时的每个节点,然后计算要删除的节点,如果是头节点就返回头节点的下一个节点(不存在即null,存在就下一个);另外一个就简单的删除节点的情况了
-
代码(1ms):
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */ class Solution { public ListNode removeNthFromEnd(ListNode head, int n) { List<ListNode> list = new ArrayList<>(); int len = 0; while(head!=null){ list.add(head); ++len; head = head.next; } int del = len-n; if(del==0){ list.get(0).next = null; if(len>1) return list.get(1); else return null; } list.get(del-1).next = list.get(del).next; list.get(del).next = null; dreturn list.get(0); } }
-
参考代码(0ms):一开始没搞懂这是什么思维,就是因为是倒数第n个,那就先让指针1走n个,后面指针2和3再一起行动,指针2比指针1完出动n个位置,就是要删除的位置前一个,而指针3就是要删除的位置。
class Solution { public ListNode removeNthFromEnd(ListNode head, int n) { ListNode fast = head, slow = head, pre = null; while(n-- > 0 && fast != null) fast = fast.next; while(fast != null) { fast = fast.next; pre = slow; slow = slow.next; } if(pre == null) return head.next; else { pre.next = pre.next.next; } return head; } }
-
参考后重写(0ms):
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */ class Solution { public ListNode removeNthFromEnd(ListNode head, int n) { ListNode pre = null,th = head,del = head; while(n-- > 0 && th != null){ th = th.next; } while(th!=null){ //这里算是一个关键吧,让pre延迟一格 pre = del; del = del.next; th = th.next; } if(pre == null) return head.next; pre.next = pre.next.next; return head; } }