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; }

 

转载于:https://www.cnblogs.com/neversayno/p/5097564.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值