zoukankan      html  css  js  c++  java
  • leetcode ---Remove Nth Node From End of List

    注意的地方:1、使用双指针操作,当第二个指针到尾部时,第一个指针的位置就是要删除位置的前一位

                     2、注意head节点的删除,如果删除head,直接使head返回null;

            

    /**
     * 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 p1 = head;
            ListNode pre = head;
            int pos = 0;
            if (head.equals(null)|| n==0)
                return head;
            if(head.next==null && n==1)
               return null; 
            for(int i = 0;i<n;i++){
                p1 = p1.next;
            }
            if(p1==null){                                 //如果当p1走到指定位置时,发现超过了链的长度,那么p1一定是null,此时,删除的是head;
                   head = head.next;
                   pre = null ;
                   return head;
            }
            while(p1.next!=null){
                p1 = p1.next;
                pre = pre.next;
            }
                pre.next = pre.next.next;    
                return head;
            }
        }

    改进方法:在head之前新建一个节点,也就是新建一个头结点永远不会删除的链表-----原链表从head.next开始!

    public ListNode removeNthFromEnd(ListNode head, int n) {
        if (head == null)
            return null;
        ListNode headCount = new ListNode(0);   
        headCount.next = head;
        head = headCount;          //在head之前新建一个节点,这个节点的值为0;这样的话,新的链表的head是这个新加的节点
    //而不是原来的head,这样就可以不用考虑头结点的处理了
    ListNode tmp = head, slow = head.next, fast = head.next; int count = 1; while (count < n) { count++; fast = fast.next; } while (fast.next != null) { fast = fast.next; slow = slow.next; tmp = tmp.next; } tmp.next = slow.next; return head.next; }
    态度决定行为,行为决定习惯,习惯决定性格,性格决定命运
  • 相关阅读:
    计算机学院大学生程序设计竞赛(2015’12)Study Words
    离散化
    一键拨打
    python中Strip()函数的用法
    笨方法学python 22,前期知识点总结
    笨方法学python之读写文件、open函数的用法
    Linux 多线程串口通信
    RSA加密前言
    GrabCut--Opencv篇
    队列
  • 原文地址:https://www.cnblogs.com/neversayno/p/5097564.html
Copyright © 2011-2022 走看看