LeetCode 热题100 19. 删除链表的倒数第N个节点

题目:

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

示例:

(图源:https://leetcode.cn/problems/remove-nth-node-from-end-of-list/)

 

解析:

其实一般思路就是找到要删除的节点temp,再找到该节点的前一个节点pre,做好pre.next = temp.next即可。

一个特判就是,如果删除的链表的第一个结点,那么直接返回head.next即可。

代码:

 1 /**
 2  * Definition for singly-linked list.
 3  * public class ListNode {
 4  *     int val;
 5  *     ListNode next;
 6  *     ListNode() {}
 7  *     ListNode(int val) { this.val = val; }
 8  *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 9  * }
10  */
11 class Solution {
12     public ListNode removeNthFromEnd(ListNode head, int n) {
13        int counter = 0;
14         ListNode tmp=new ListNode();
15         ListNode pre=new ListNode();
16         tmp = head;
17         while(tmp!=null){
18             counter++;
19             tmp=tmp.next;
20         }
21         if(counter==n){
22             return head.next;
23         }
24         else{
25             tmp = head;
26             for(int i=0;i<counter-n;++i){
27                 pre = tmp;
28                 tmp=tmp.next;
29             }
30             pre.next=tmp.next;
31             return head;
32         }
33     }
34 }

 

posted @ 2022-06-24 20:30  Tiancfq  阅读(15)  评论(0编辑  收藏  举报