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

95 阅读1分钟

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

image.png

  • 解题思路:

    1. 统计当前列表的长度 使用一个变量记录 count
    2. 要考虑的边界问题 如果 count < n 证明已经超过了这个链表的长度,直接返回null
    3. 如果 n == count 证明要删除的是头节点 , 此时需要返回头节点的下一个节点
    4. 使用 count - n 计算出来头节点到目标节点的前一个节点需要走几步
    5. 然后使用目标节点的.next = 目标节点.next.next
    6. 最后返回head头节点
  • Coding

public class RemoveNthFromEnd_19 {

   public static class ListNode {
     int val;
     ListNode next;
     ListNode() {}
     ListNode(int val) { this.val = val; }
     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
   }

   public static ListNode removeNthFromEnd(ListNode head, int n) {
       if (head == null){
           return head;
       }
       //记录头节点
       ListNode cur = head;
       //1.统计链表的长度
       int count = 0;
       while(cur!=null){
           count++;
           cur = cur.next;
       }
       if (n>count){
           return null;
       }
       if (n == count){
           return head.next;
       }
       //2.计算出来头节点到目标节点差几步
       int target = count - n;
       cur = head;
       while(target>1){
           target--;
           cur = cur.next;
       }
       cur.next = cur.next.next;
       return head;
   }
   //Test Case
   public static void main(String[] args) {
       ListNode root = new ListNode(1);
       ListNode root2 = new ListNode(2);
       ListNode root3 = new ListNode(3);
       ListNode root4 = new ListNode(4);
       ListNode root5 = new ListNode(5);
       root.next = root2;
       root2.next = root3;
       root3.next = root4;
       root4.next = root5;
       ListNode listNode = removeNthFromEnd(root, 5);
       while(listNode!=null){
           System.out.print(listNode.val + " ===> ");
           listNode = listNode.next;
       }
   }
}