给你一个链表,删除链表的倒数第 n
个结点,并且返回链表的头结点。
进阶:你能尝试使用一趟扫描实现吗?
输入:head = [1,2,3,4,5], n = 2 输出:[1,2,3,5]
解:
class Solution {
public ListNode removeNthFromEnd(ListNode head, int n) {
ListNode dummy = new ListNode(0, head);
ListNode first = head;
ListNode second = dummy;
for (int i = 0; i < n; ++i) {
first = first.next;
}
while (first != null) {
first = first.next;
second = second.next;
}
second.next = second.next.next;
ListNode ans = dummy.next;
return ans;
}
}
/*
作者:LeetCode-Solution
链接:https://leetcode-cn.com/problems/remove-nth-node-from-end-of-list/solution/shan-chu-lian-biao-de-dao-shu-di-nge-jie-dian-b-61/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。*/
下记代码用于idea debug:
public class No19_removeNthFromEnd_j {
public static void main(String[] args) {
ListNode listNode1 = new ListNode(1);
ListNode listNode2 = new ListNode(2);
ListNode listNode3 = new ListNode(3);
ListNode listNode4 = new ListNode(4);
ListNode listNode5 = new ListNode(5);
head.add(listNode1);
head.add(listNode2);
head.add(listNode3);
head.add(listNode4);
head.add(listNode5);
//head.list();
ListNode node = head.removeNthFromEnd(3);
System.out.println(node.toString());
}
}
class head{
public static ListNode head = new ListNode(0, null);
//--> 删除倒数第N个节点
public static ListNode removeNthFromEnd( int n) {
ListNode dummy = new ListNode(0, head.next);
ListNode first = head.next;
ListNode second = dummy;
for (int i = 0; i < n; ++i) {
first = first.next;
}
while (first != null) {
first = first.next;
second = second.next;
}
second.next = second.next.next;
ListNode ans = dummy.next;
return ans;
}
public static void add(ListNode listNode) {
//因为head节点不能动,因此我们需要一个辅助遍历 temp
ListNode temp = head;
while (true) {
//找到链表的最后
if (temp.next == null) {
break;
}
//如果没有找到最后, 将将temp后移
temp = temp.next;
}
//当退出while循环时,temp就指向了链表的最后
//将最后这个节点的next 指向 新的节点
temp.next = listNode;
}
public static int size(){
if (head.next == null){
return 0;
}
int length = 0;
ListNode icur = head.next;
while (icur != null){
length++;
icur = icur.next;
}
return length;
}
//显示链表[遍历]
public static void list() {
//判断链表是否为空
if(head.next == null) {
System.out.println("链表为空");
return;
}
//因为头节点,不能动,因此我们需要一个辅助变量来遍历
ListNode temp = head.next;
while(true) {
//判断是否到链表最后
if(temp == null) {
break;
}
//输出节点的信息
System.out.println(temp);
//将temp后移, 一定小心
temp = temp.next;
}
}
}
class ListNode {
public int val;
public ListNode next;
public ListNode() {}
public ListNode(int val) { this.val = val; }
public ListNode(int val, ListNode next) { this.val = val; this.next = next; }
public String toString() {
return "ListNode{" +
"val=" + val +
", " +
"next=" + next +
'}';
}
}