LeetCode(46)-Remove Nth Node From End of List

时间:2023-12-17 19:35:44

题目:

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,然后倒数去掉第n个数字,返回head
  • 利用双指针,一个first先走n个,然后next在和first同步走,等到first.next != null;这时next正好指向要去掉元素的前一个,next.next = next.next.next;
  • 注意去掉head的情况和链表为0和1

代码:

/**
 * 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) {
        if(head == null||head.next == null){
            return null;
        }
        ListNode prev = head;
        ListNode next = head;
        for(int i = 0;i < n;i++){
            prev = prev.next;
        }
        if(prev == null){
            head = head.next;
            return head;
        }
        while(prev.next != null){
            prev = prev.next;
            next = next.next;
        }
        next.next = next.next.next;
        return head;
    }
}