删除链表的倒数第N个结点
给你一个链表,删除链表的倒数第 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]
(上述题目来源于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) {
//两次遍历,第一次遍历得到链表结点个数,第二次遍历指针到达结点个数-n时,
//移除指针后面的结点
int count = 0;
ListNode newHead = new ListNode(0,head);
ListNode point = newHead;
while(head != null){
head = head.next;
count++;
}
for(int i = 0;i < count - n;i++){
point = point.next;
}
point.next = point.next.next;
return newHead.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) {
//双指针思想
//使second指针从哑结点处开始,使first指针先走n步,然后两个指针再一起走,
//那么,当first指针走到尽头时,second指针指向倒数第n个结点的前驱结点
//此时再移除second后的结点即可
ListNode point = new ListNode(0,head);
ListNode first = head;
ListNode second = point;
for(int i = 0;i < n;i++){
first = first.next;
}
while(first != null){
first = first.next;
second = second.next;
}
second.next = second.next.next;
return point.next;
}
}