zoukankan      html  css  js  c++  java
  • Lintcode174-Remove Nth Node From End of List-Easy

    174. Remove Nth Node From End of List

    Given a linked list, remove the nth node from the end of list and return its head.

    Example

    Example 1:
    	Input: list = 1->2->3->4->5->null, n = 2
    	Output: 1->2->3->5->null
    
    
    Example 2:
    	Input:  list = 5->4->3->2->1->null, n = 2
    	Output: 5->4->3->1->null
    
    

    Challenge

    Can you do it without getting the length of the linked list?

    Notice

    The minimum number of nodes in list is n.

    双指针法:

    定义快慢指针,先同时指向dummy结点。快指针(head)先比慢指针(preDelete)多走n步。

    然后,快慢指针一起走,当快指针指向链表最后一个结点时,慢指针指向就是要删除结点的前一个结点。

    ps: 对单向链表而言,删除结点时,必须操作要删除结点的前一个结点,而不是要删除的结点本身,否则无法使要删除结点的前一个和后一个结点连接。这也是这个题中,慢指针指向要删除结点的前一个结点,也因此推出快指针的临界位置。

    代码:

    public ListNode removeNthFromEnd(ListNode head, int n) {
        ListNode dummy = new ListNode(-1);
        dummy.next = head;
        head = dummy;
        ListNode preDelete = dummy;
        
        for (int i = 1; i <= n; i++) {
            head = head.next;
        }
        while (head.next != null) {
            head = head.next;
            preDelete = preDelete.next;
        }
        preDelete.next = preDelete.next.next;
        return dummy.next;
    }

    考虑特殊情况(n <= 0, head == null)

    public class Solution {
        public ListNode removeNthFromEnd(ListNode head, int n) {
            if (n <= 0) {
                return null;
            }
            
            ListNode dummy = new ListNode(0);
            dummy.next = head;
            
            ListNode preDelete = dummy;
            for (int i = 0; i < n; i++) {
                if (head == null) {
                    return null;
                }
                head = head.next;
            }
            while (head != null) {
                head = head.next;
                preDelete = preDelete.next;
            }
            preDelete.next = preDelete.next.next;
            return dummy.next;
        }
    }
  • 相关阅读:
    C# 获取电脑SN号
    Windows 使用ffmpeg将MP4视频转换为m3u8格式
    C# 创建或打开TXT文件并逐行写入
    Dictionary通过下标获取key和value
    Winfrom 连接考勤机设备时界面假死
    Win 10操作系统快捷键
    SQL Server 2008 在表中插入新的字段
    什么是CSR
    Sql Server中的事务隔离级别
    Web验证方式(4)--JWT
  • 原文地址:https://www.cnblogs.com/Jessiezyr/p/10741030.html
Copyright © 2011-2022 走看看