题目:给你一个链表,删除链表的倒数第 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]
提示:
- 链表中结点的数目为 sz
- 1 <= sz <= 30
- 0 <= Node.val <= 100
- 1 <= n <= sz
题目来源:力扣(LeetCode)链接
题解:
- 自己做的
/** * 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) { int size = 0;//首先遍历链表,记录链表的总长度 ListNode countNode = head; while (countNode != null) { size++; countNode = countNode.next; } //定义一个虚拟头节点 ListNode dummyNode = new ListNode(-1); dummyNode.next = head; //查找倒数第n个节点的前一个节点 ListNode prevNode = dummyNode; for (int i = 0; i < size - n; i++) { prevNode = prevNode.next; } //删除该节点 prevNode.next = prevNode.next.next; //返回链表的真实头节点 return dummyNode.next; } }
- 双指针法
/** * 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 dummyNode = new ListNode(-1); dummyNode.next = head; //定义快指针和慢指针 ListNode fastNode = dummyNode; ListNode slowNode = dummyNode; //让快指针前移n个,保证其与慢指针之间相隔n个节点 for (int i = 0; i < n; i++) { fastNode = fastNode.next; } //快指针指向最后一个节点时,慢指针正好指向倒数第n个节点的前一节点,因为快慢指针之间始终相隔n个节点 while (fastNode.next != null) { fastNode = fastNode.next; slowNode = slowNode.next; } //删除倒数第n个节点 slowNode.next = slowNode.next.next; //返回链表的真实头节点 return dummyNode.next; } }