leetcode 双指针 删除链表的倒数第N个节点 Java

题目描述
给定一个链表,删除链表的倒数第 n 个节点,并且返回链表的头结点。
示例:
给定一个链表: 1->2->3->4->5, 和 n = 2.
当删除了倒数第二个节点后,链表变为 1->2->3->5.

思路一:
先求出链表的长度

 private int length(ListNode head){
    
    
        int len = 0;
        while(head != null){
    
    
            len++;
            head = head.next;
        }
        return len;
    }

找到要删除链表的前一个节点
将该节点指向删除节点的下一个节点
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
代码:

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

思路2:
双指针:
一个指针fast先走n步,然后另一个指针slow从头开始,找到要删除节点的前一个节点n,然后n.next = n.next.next

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

猜你喜欢

转载自blog.csdn.net/stonney/article/details/111870097
今日推荐