• [LeetCode] 19. Remove Nth Node From End of List ☆


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

    For 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.
    Try to do this in one pass.

    解法:

      题目要求移除倒数第n个节点,并且说明了n一定是有效的,限定一次遍历解决问题。首先定义两个指针 first 和 last,first 指向第一个节点,last 指向第 n+1 个节点;两个节点同时向后撸,直到 last.next 为 null 的时候,说明当前 first.next 即为待删除节点,直接 first.next.next = first.next 即可删除,然后返回 head。注意,如果一开始的时候 last 就为 null,说明 head 节点就是带删除的节点,直接返回 head.next 即可。

    /**
     * Definition for singly-linked list.
     * public class ListNode {
     *     int val;
     *     ListNode next;
     *     ListNode(int x) { val = x; }
     * }
     */
    public class Solution {
        public ListNode removeNthFromEnd(ListNode head, int n) {
            ListNode first = head;
            ListNode last = head;
            while (n-- > 0) {
                last = last.next;
            }
            
            if (last == null) {
                return head.next;
            }
            
            while (last.next != null) {
                first = first.next;
                last = last.next;
            }
            
            first.next = first.next.next;
            return head;
        }
    }
  • 相关阅读:
    cf B. Sereja and Suffixes
    cf E. Dima and Magic Guitar
    cf D. Dima and Trap Graph
    cf C. Dima and Salad
    最短路径问题(floyd)
    Drainage Ditches(网络流(EK算法))
    图结构练习—BFSDFS—判断可达性(BFS)
    Sorting It All Out(拓扑排序)
    Power Network(最大流(EK算法))
    Labeling Balls(拓扑)
  • 原文地址:https://www.cnblogs.com/strugglion/p/6413585.html
Copyright © 2020-2023  润新知