zoukankan      html  css  js  c++  java
  • LeetCode19----删除链表的指定元素

    给定一个链表,删除链表的倒数第 个节点,并且返回链表的头结点。

    示例:

    给定一个链表: 1->2->3->4->5, 和 n = 2.
    
    当删除了倒数第二个节点后,链表变为 1->2->3->5.
    

    说明:

    给定的 n 保证是有效的。

    进阶:

    你能尝试使用一趟扫描实现吗?

           该题目的要求是只需要扫描一次就可以实现,那么我们就不可能去创建一个数组来解决该问题,因为把链表元素全部放进数组就要扫描一次,而把删除后的数组放入链表又要扫描一次,所以我们这里采用创建额外的指针来解决该问题!!

    代码如下:

    public class LeetCode19 {
    	public static class ListNode {
    		int val;
    		ListNode next;
    
    		ListNode(int x) {
    			val = x;
    		}
    	}
    
    	public ListNode removeNthFromEnd(ListNode head, int n) {
    		if (head == null) {
    			return null;
    		}
    		int k = 0;
    		ListNode low = head;
    		ListNode fast = head;
    		while (k < n - 1) {
    			fast = fast.next;
    			k++;
    		}
    		ListNode lastLow = null;
    		while (true) {
    			if (fast.next != null) {
    				fast = fast.next;
    				lastLow = low;
    				low = low.next;
    			} else {
    				if (lastLow == null) {
    					return low.next;
    				} else {
    					lastLow.next = low.next;
    					low.next = null;
    					return head;
    				}
    			}
    		}
    	}
    }
    

      

  • 相关阅读:
    nginx
    VSFTPD
    Dubbo
    ZooKeeper
    maven
    linux 学习
    Shiro安全框架
    Jqueryの锋利的jquery练习
    Java中的数组操作进阶
    Java IO总结之缓冲读入文件
  • 原文地址:https://www.cnblogs.com/Booker808-java/p/9085433.html
Copyright © 2011-2022 走看看