美文网首页
LeetCode实战:删除链表的倒数第N个节点

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

作者: 老马的程序人生 | 来源:发表于2019-04-16 10:32 被阅读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;
        }
    }
    
    提交记录

    相关图文

    相关文章

      网友评论

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

          本文链接:https://www.haomeiwen.com/subject/okjvwqtx.html