LeetCode Hot100 19. 删除链表的倒数第 N 个结点

题目

给你一个链表,删除链表的倒数第 n 个结点,并且返回链表的头结点。

方法一(自己想的,倒数变正着数)

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
class Solution {
    public ListNode removeNthFromEnd(ListNode head, int n) {
        ListNode node = head;
        int length = 0;
        while(node != null){
            node = node.next;
            length += 1;
        }
        int j = length - n + 1; // 将倒数换成正数
        length = 0;
        node = head;
        while(node != null && node.next != null){
            length += 1;
            ListNode mid = node.next;
            if(length == j-1){
                node.next = mid.next;
                mid = null;
                return head;
            }
            if(j-1 == 0)
                return mid;
            node = node.next;
        }
        return null;
    }
}

方法二(灵神)4    2         1  2  3   4     右3  

思想:左右指针,右指针先走n步,然后左右一起走length-n-1步,右指针到表尾,左指针到倒数第n+1个位置。

class Solution {
    public ListNode removeNthFromEnd(ListNode head, int n) {
        ListNode dummy = new ListNode(0, head);
        ListNode left = dummy, right = dummy;
        while (n-- > 0)
            right = right.next;
        while (right.next != null) {
            left = left.next;
            right = right.next;
        }
        left.next = left.next.next;
        return dummy.next;
    }
}

你可能感兴趣的:(算法刷题-链表,leetcode,链表,算法)