题目
题解
代码
/** * Definition for singly-linked list. public class ListNode { int val; ListNode * next; ListNode(int x) { val = x; } } */
public class code19 {
// public static ListNode removeNthFromEnd(ListNode head, int n) {
// ListNode dummy = new ListNode(0);
// dummy.next = head;
// // 获取链表长度
// int len = 0;
// ListNode first = head;
// while (first != null) {
// len++;
// first = first.next;
// }
// // 找到角标为(length - n - 1)的结点,让其next指向下下一个结点。
// len = len - n;
// first = dummy;
// while (len > 0) {
// len--;
// first = first.next;
// }
// first.next = first.next.next;
// return dummy.next;
// }
public static ListNode removeNthFromEnd(ListNode head, int n) {
ListNode dummy = new ListNode(0);
dummy.next = head;
ListNode first = dummy;
ListNode second = dummy;
// 前进第一个指针,使第一个指针和第二个指针之间的间隙为n个节点
for (int i = 1; i <= n + 1; i++) {
first = first.next;
}
// 移动第一个指针到链表的末端,保持两个指针的间隙为n个节点
while (first != null) {
first = first.next;
second = second.next;
}
second.next = second.next.next;
return dummy.next;
}
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);
listNode1.next = listNode2;
listNode2.next = listNode3;
listNode3.next = listNode4;
listNode4.next = listNode5;
System.out.println(listNode1.val + " -> " + listNode2.val + " -> " + listNode3.val + " -> " + listNode4.val
+ " -> " + listNode5.val);
int n1 = 2;
ListNode result1 = removeNthFromEnd(listNode1, n1);
System.out.println(result1.val + " -> " + result1.next.val + " -> " + result1.next.next.val + " -> "
+ result1.next.next.next.val);
}
}