LeetCode实战:删除链表的倒数第N个节点
发布日期:2021-06-30 22:56:52
浏览次数:3
分类:技术文章
本文共 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 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!
发表评论
最新留言
做的很好,不错不错
[***.243.131.199]2024年05月04日 15时37分30秒
关于作者
喝酒易醉,品茶养心,人生如梦,品茶悟道,何以解忧?唯有杜康!
-- 愿君每日到此一游!
推荐文章
COMP7404 Machine Learing——ROC
2019-04-30
YAPF —— Python代码格式化工具
2019-04-30
slurm
2019-04-30
MATLAB与CUDA
2019-04-30
Linux png转jpg (convert命令)
2019-04-30
Ubuntu更新后终端中字体的颜色全是白色
2019-04-30
vscode git
2019-04-30
基于MATLAB的二进制数字调制与解调信号的仿真——2PSK
2019-04-30
基于MATLAB的模拟调制信号与解调的仿真——DSB
2019-04-30
HDU - 1166 敌兵布阵 (树状数组模板题/线段树模板题)
2019-04-30
CodeForces - 761C Dasha and Password (思维 暴力)
2019-04-30
POJ - 2481 Cows (树状数组 入门题)
2019-04-30
CodeForces - 987C Three displays (暴力/dp)
2019-04-30
计蒜客 NAIPC 2016 F. Mountain Scenes(dp)
2019-04-30
牛客国庆集训派对Day4——I 连通块计数(思维)
2019-04-30
牛客国庆集训派对Day4——G 区间权值(找规律,双重前缀和)
2019-04-30