zoukankan      html  css  js  c++  java
  • 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.

    大概思路:

    1)用p,q两个指针来记录2个位置,p,q初始化为head;

    2)然后p先不动,q向后移动n个位置;

    3)接着p,q以同样的步伐一起向链表尾部移动,直到q到达链表尾部,即q.next==null;

    4)此时p是待删除节点的前驱,修改p.next即可。

    这里一个细节要考虑,若n等于节点数,即删除倒数第n个也就是第1个节点,那么在第2)步q会移动到尾部节点下一个位置即q==null,所以移动时加个判断即可。

    /**
     * Definition for singly-linked list.
     * public class ListNode {
     *     int val;
     *     ListNode next;
     *     ListNode(int x) {
     *         val = x;
     *         next = null;
     *     }
     * }
     */
    public class Solution {
        public ListNode removeNthFromEnd(ListNode head, int n) {
            ListNode p = head;
            ListNode q = head;
            while(n!=0){
                q = q.next;
                //如果q==null说明n==List.length,即删除第一个节点
                if(q==null){
                    return head.next;
                }
                n--;
            }
            while(q.next!=null){
                p = p.next;
                q = q.next;
            }
            ListNode temp = p.next;
            p.next = temp.next;
            return head;
        }
    }
  • 相关阅读:
    053403
    053402
    053401
    053400
    053399
    053398
    053397
    053396
    053395
    第k小数
  • 原文地址:https://www.cnblogs.com/mrpod2g/p/4265356.html
Copyright © 2011-2022 走看看