• 19. Remove Nth Node From End of List


    public ListNode removeNthFromEnd(ListNode head, int n) {
            if (head.next == null)  return null;
            List<ListNode> l = new ArrayList<>();
            while (head != null){
                l.add(head);
                head = head.next;
            }
            if (n == 1){
                ListNode br = l.get(l.size() - 2);
                br.next = null;
                return l.get(0);    
            }
            else if(n == l.size())
                return l.get(1);
            else{
                ListNode fr = l.get(l.size() - n - 1);  //n == n
                ListNode br = l.get(l.size() - n + 1);  //n == 1
                fr.next = br;
                return l.get(0);    
            }
        }
    

    利用快慢指针:
    这里快指针要走n+1步,会出现走过界的情况,就在他们前面加入一个start节点,完全不影响,因为slow和fast始终差n.

    public ListNode removeNthFromEnd(ListNode head, int n) {
            //利用快慢指针
            ListNode start = new ListNode(0);
            ListNode slow = start, fast = start;
            slow.next = head;
            //slow,fast 相隔n个,让fast 先走n+1步
            for (int i=0; i <= n ; i++)
                fast = fast.next;
            
            while (fast != null){
                fast = fast.next;
                slow = slow.next;
            }
            
            slow.next = slow.next.next;
            return start.next;
        }
    
  • 相关阅读:
    两种方法生成随机字符串
    cmd命令总结
    NOI前乱写
    多校模拟9
    字符串 口胡
    HEOI2020游记
    省选模拟104
    省选模拟103
    省选模拟102
    省选模拟101
  • 原文地址:https://www.cnblogs.com/whyaza/p/10670249.html
Copyright © 2020-2023  润新知