版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Tc_To_Top/article/details/88524793
Given a linked list, remove the n-th node from the end of list and return its head.
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.
Follow up:
Could you do this in one pass?
题目链接:https://leetcode.com/problems/remove-nth-node-from-end-of-list/
题目分析:fir先前进n,然后和sec一起前进,注意判断删除的是表头的情况
5ms,时间击败100%
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode removeNthFromEnd(ListNode head, int n) {
ListNode fir = head;
ListNode sec = head;
while (fir.next != null) {
if (n > 0) {
n--;
} else {
sec = sec.next;
}
fir = fir.next;
}
if (n > 0) {
return head.next;
}
if (sec.next != null) {
sec.next = sec.next.next;
}
return head;
}
}