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 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!

上一篇:如何利用 C# 爬取「财报说」中的股票数据?
下一篇:图书排行:计算机书籍每周销量排行榜

发表评论

最新留言

路过,博主的博客真漂亮。。
[***.116.15.85]2024年04月30日 10时58分02秒

关于作者

    喝酒易醉,品茶养心,人生如梦,品茶悟道,何以解忧?唯有杜康!
-- 愿君每日到此一游!

推荐文章