LeetCode实战:删除链表的倒数第N个节点

2019-04-16  本文已影响0人  老马的程序人生

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;
    }
}
提交记录

相关图文

上一篇 下一篇

猜你喜欢

热点阅读