zoukankan      html  css  js  c++  java
  • Leetcode之删除链表的倒数第N个节点

    问题描述

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

    示例:

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

    说明:

    给定的 n 保证是有效的。

    进阶:

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

    解法

    双指针,当遍历指针前进n个时,后面一个指针指向头部,这样保证了当遍历指针到达尾部时,后面一个指针在倒数第n个上,但是因为我们需要的是倒数第n个指针的前一个指针。所以我们再多等一次。但是这个时候就会出现边界性的问题,如果倒数第n个指针是头指针的下一个指针,但我们此时还没有后一个指针(q.next= =null跳出),所以head.next=head.next.next(n= =0)(此时q就是head);如果仅有一个数,即删除头指针时,head=head.next(q.next== null,n > 0)。

    /**
     * Definition for singly-linked list.
     * public class ListNode {
     *     int val;
     *     ListNode next;
     *     ListNode(int x) { val = x; }
     * }
     */
    class Solution {
        public ListNode removeNthFromEnd(ListNode head, int n) {
            ListNode q=head;
            ListNode p=null;
            while(q.next!=null){
                if(n>0){
                    q=q.next;
                    n--;
                }else if(n==0){
                   p=head;
                   n--;
                }else{
                    p=p.next;
                    q=q.next;
                }
            } 
            
            if(n>0){
                head=head.next;
            }else if(n==0){
                head.next=head.next.next;
            }else{
                p.next=p.next.next;
            }
            return head;
        }
    }
    

    结果

  • 相关阅读:
    poj 3616 Milking Time
    poj 3176 Cow Bowling
    poj 2229 Sumsets
    poj 2385 Apple Catching
    poj 3280 Cheapest Palindrome
    hdu 1530 Maximum Clique
    hdu 1102 Constructing Roads
    codeforces 592B The Monster and the Squirrel
    CDOJ 1221 Ancient Go
    hdu 1151 Air Raid(二分图最小路径覆盖)
  • 原文地址:https://www.cnblogs.com/code-fun/p/13701035.html
Copyright © 2011-2022 走看看