LeetCode实战:删除链表的倒数第N个节点
发布日期:2021-06-30 22:56:52
浏览次数:2
分类:技术文章
本文共 2125 字,大约阅读时间需要 7 分钟。
Given a linked list, remove the n-th node from the end of list and return its head.
Example:
Given linked list: 1->2->3->4->5, and n = 2.
After removing the second node from the end, the linked list becomes 1->2->3->5.
Note:
Given n will always be valid.
Follow up:
Could you do this in one pass?
给定一个链表,删除链表的倒数第 n 个节点,并且返回链表的头结点。
示例:
给定一个链表: 1->2->3->4->5, 和 n = 2.
当删除了倒数第二个节点后,链表变为 1->2->3->5.
说明:
给定的 n 保证是有效的。
进阶:
你能尝试使用一趟扫描实现吗?
第一个版本:
/** * Definition for singly-linked list. * public class ListNode { * public int val; * public ListNode next; * public ListNode(int x) { val = x; } * } */ public class Solution{ public ListNode RemoveNthFormEnd(ListNode head, int n) { int len = GetLength(head); int index = len - n; if (index == 0) { head = head.next; return head; } ListNode temp = head; for (int i = 0; i < index - 1; i++) { temp = temp.next; } temp.next = temp.next.next; return head; } public int GetLength(ListNode head) { ListNode temp = head; int i = 0; while (temp != null) { i++; temp = temp.next; } return i; }}
第二个版本:
/** * Definition for singly-linked list. * public class ListNode { * public int val; * public ListNode next; * public ListNode(int x) { val = x; } * } */public class Solution{ public ListNode RemoveNthFormEnd(ListNode head, int n) { ListNode temp1 = head; ListNode temp2 = head; int len = 0; int index = 0; while (temp1 != null) { temp1 = temp1.next; len++; if (index == n) { break; } index++; } if (len == n) { head = head.next; return head; } while (temp1 != null) { temp1 = temp1.next; temp2 = temp2.next; } temp2.next = temp2.next.next; return head; }}
相关图文:
转载地址:https://lsgogroup.blog.csdn.net/article/details/89328533 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!
发表评论
最新留言
路过,博主的博客真漂亮。。
[***.116.15.85]2024年04月30日 10时58分02秒
关于作者
喝酒易醉,品茶养心,人生如梦,品茶悟道,何以解忧?唯有杜康!
-- 愿君每日到此一游!
推荐文章
java http请求
2019-04-30
tensorflow 数据格式
2019-04-30
tf rnn layer
2019-04-30
tf input layer
2019-04-30
tf model create
2019-04-30
tf dense layer两种创建方式的对比和numpy实现
2019-04-30
tf initializer
2019-04-30
tf 从RNN到BERT
2019-04-30
tf keras SimpleRNN源码解析
2019-04-30
tf keras Dense源码解析
2019-04-30
tf rnn输入输出的维度和权重的维度
2019-04-30
检验是否服从同一分布
2019-04-30
tf callbacks
2019-04-30
keras、tf、numpy实现logloss对比
2019-04-30
MyBatisPlus简单入门(SpringBoot)
2019-04-30
攻防世界web进阶PHP2详解
2019-04-30
攻防世界web进阶区web2详解
2019-04-30
xss-labs详解(上)1-10
2019-04-30
xss-labs详解(下)11-20
2019-04-30
攻防世界web进阶区ics-05详解
2019-04-30