Given a linked list, remove the nth node from the end of list and return its head.
For example,
Given linked list: 1->2->3->4->5, and n = 2.
After removing the second node from the end, the linked list becomes 1->2->3->5.
Note:Given n will always be valid.Try to do this in one pass
给定一个链表,移除从链表末尾起的第n个节点,并返回链表head
方法一
算法分析
- 首先需要一个dummy节点,指向链表head位置,主要是为了在链表长度为1时简化代码。
- 要删除的节点在
L-n+1
位置(L为链表长度
)。 - 找到第
L-n
个节点,指向L-n+2
个节点。
答案
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class Solution {
public ListNode removeNthFromEnd(ListNode head, int n) {
ListNode dummy = new ListNode(0);
dummy.next = head;
ListNode current = head;
int length = 0;//链表长度
while (current != null) {
length ++;//寻找链表长度
current = current.next;
}
length = length - n;//到要被删除位置的链表节点的前一个
current = dummy;
while (length > 0) {
length --;
current = current.next;
}
current.next = current.next.next;//将被删除的节点前一个节点指向被删除节点的下一个节点
return dummy.next;
}
}
方法二
算法分析
- first、second两个节点指向head
- 移动first节点到与second相差n个节点的位置
- 同时移动first、second直到first为null
- 此时second的下一个节点是为要删除的节点
答案
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class Solution {
public ListNode removeNthFromEnd(ListNode head, int n) {
ListNode dummy = new ListNode(0);
ListNode first = dummy;
ListNode second = dummy;
dummy.next = head;
for (int i = 1; i <= n + 1; i++) {
first = first.next;//将first移到与second相差n个节点
}
while (first != null) {//first和second同时移动,直到first到最后一个节点的下一个节点
first = first.next;
second = second.next;
}
second.next = second.next.next;
return dummy.next;
}
}