题目:给你一个链表,删除链表的倒数第 n
个结点,并且返回链表的头结点。
示例 1:
输入:head = [1,2,3,4,5], n = 2
输出:[1,2,3,5]
示例 2:
输入:head = [1], n = 1
输出:[]
示例 3:
输入:head = [1,2], n = 1
输出:[1]
算法:(1)进行一次遍历,在遍历途中使用一个map来进行编号存储,编号从1开始,删除的节点就为链表长度-n+1。
算法:(2)使用双指针,fast指针比slow指针快n个长度,那么当fast指针指向链表末尾的时候,slow指针刚好指向倒数第n个节点。
代码实现:
(1)
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode() {} * ListNode(int val) { this.val = val; } * ListNode(int val, ListNode next) { this.val = val; this.next = next; } * } */ class Solution { public ListNode removeNthFromEnd(ListNode head, int n) { if(head.next == null){ return null; } ListNode temp = head; ListNode res = temp; int index = 1; Map<Integer, ListNode> map = new HashMap<Integer, ListNode>(); while(head.next != null){ map.put(index, head); head = head.next; index++; } if(n == index){ return res.next; } ListNode node = map.get(index - n); if(node.next.next != null){ node.next = node.next.next; }else{ node.next = null; } while(temp != node){ temp = temp.next; } temp.next = node.next; return res; } } (2) /** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode() {} * ListNode(int val) { this.val = val; } * ListNode(int val, ListNode next) { this.val = val; this.next = next; } * } */ class Solution { public ListNode removeNthFromEnd(ListNode head, int n) { ListNode res = new ListNode(0,head); ListNode fast = head; ListNode slow = res; if(head.next == null){ return null; } for(int i = 0; i < n; i++){ fast = fast.next; } while(fast != null){ fast = fast.next; slow = slow.next; } slow.next = slow.next.next; return res.next; } }