1. 程式人生 > 其它 >【每日一題】2021年12月13日-19. 刪除連結串列的倒數第 N 個結點

【每日一題】2021年12月13日-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 fast = head; ListNode slow = head; while(n-- > 0) { fast = fast.next; } if(fast == null) { //表示刪除的是第一個節點 return head.next; } fast = fast.next;//
重要,使slow在待刪除的前一個節點 while(fast != null) { fast = fast.next; slow = slow.next; } //刪除節點 slow.next = slow.next.next; return head; } }

本文來自部落格園,作者:劉金輝,轉載請註明原文連結:https://www.cnblogs.com/liujinhui/p/15684031.html