• Welcome to the world's largest Chinese hacker forum

    Welcome to the world's largest Chinese hacker forum, our forum registration is open! You can now register for technical communication with us, this is a free and open to the world of the BBS, we founded the purpose for the study of network security, please don't release business of black/grey, or on the BBS posts, to seek help hacker if violations, we will permanently frozen your IP and account, thank you for your cooperation. Hacker attack and defense cracking or network Security

    business please click here: Creation Security  From CNHACKTEAM

[链表] [leetCode高频] : 19 删除链表底部的第n个节点


Recommended Posts

1、题目描述

给你一个链表,删除链表底部第n个节点,返回链表的头节点。

j0gfq4iqdg03709.png

2、算法分析

知识补充:

nqqi3ckab5f3710.png

分析:

题目是删除链表底部的第n个节点。你可以使用慢速和快速两种指针。

重点是找到被删除结点的前一个结点。.

(1)定义一个头节点来头

慢指向头节点,快指向头节点。首先后退n位,然后慢速和快速指针节点一起后退n位。当fast指向空时,slow指向要删除的节点的前一位。

定义ListNode slow=dummy。这个错开一个地方。当fast指针指向链表的最后一位时,slow只是被删除节点的前一位。

3、代码实现

1 /**

2 *单链表的定义。

3 *公共类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类解决方案{

12 public ListNode removeNthFromEnd(list node head,int n) {

13 ListNode dummy=new ListNode(0,head);

14 ListNode slow=dummy

15 ListNode fast=head

16

17 for(int I=1;I=n;i ){

18 fast=fast.next

19 }

20

21 while(快!=null){

22 slow=slow.next

23 fast=fast.next

24 }

25 slow . next=slow . next . next;

26返回dummy.next

27 }

28 }

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now