leetcode19.删除链表的倒数第N个结点——学习笔记
2021/11/3 23:09:53
本文主要是介绍leetcode19.删除链表的倒数第N个结点——学习笔记,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
题目:力扣https://leetcode-cn.com/problems/remove-nth-node-from-end-of-list/
/** * 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 temp = new ListNode(0, head); int length = getLength(head); ListNode cur = temp; for (int i=1;i<length-n+1;i++) { cur = cur.next; } cur.next = cur.next.next; ListNode ans = temp.next; return ans; } public int getLength(ListNode head) { int length = 0; while (head!=null) { head = head.next; length++; } return length; } }
思路:先计算传入的head链表有多长,然后使cur去到指定的倒数位置,然后将要删去结点的头和尾的结点直接相连,用ans指向操作后的链表,最后返回ans即可。
1.先写一个获取链表长度的数组getLength()。遍历链表,然后用length记录长度,最后返回length。
public int getLength(ListNode head) { int length = 0; while (head!=null) { head = head.next; length++; } }
2. 准备工作。声明一个temp和一个cur,temp是指向传入链表的头结点,而cur是指向需要操作的结点。计算传入链表长度需要调用getLength()方法。
ListNode temp = new ListNode(0, head); int length = getLength(head); ListNode cur = temp;
3.用循环将cur移动到指定位置(需要删除结点的上一个结点)。将cur.next的值修改成需要删除的结点的下一个结点的值。用ans指向完成删除操作的链表temp.next(需要.next是因为temp有头结点,头结点不需要返回,因此从头结点的下一个结点开始。)最后返回ans即可。
for (int i=1;i<length-n+1;i++) { cur = cur.next; } cur.next = cur.next.next; ListNode ans = temp.next; return ans; }
这篇关于leetcode19.删除链表的倒数第N个结点——学习笔记的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-07-05feign默认connecttimeout和readtimeout是多少-icode9专业技术文章分享
- 2024-07-05idea控制台,日志太多,导致部分想看得日志被刷走 搜不到-icode9专业技术文章分享
- 2024-07-05The server selected protocol version Tls10 is not accepted by client preferences [TLs12]-icode9专业技术文章分享
- 2024-07-05怎么清理项目缓存-icode9专业技术文章分享
- 2024-07-04安装 Eyoucms详细图文教程-icode9专业技术文章分享
- 2024-07-04ueditor 复制文章时,图片的链接是一个下载图片地址,该如何处理?-icode9专业技术文章分享
- 2024-07-04怎样判断host有没有对wordpress有缓存呢-icode9专业技术文章分享
- 2024-07-04具有编译功能的系统make后,无法ssh连接-icode9专业技术文章分享
- 2024-07-04make后如何升级ssh-icode9专业技术文章分享
- 2024-07-03微信支付提示下单账户与支付账户不一致-icode9专业技术文章分享